8

I am trying to remove entries from a Hashmap, if i have already used them. Sadly, I'm not familier with Java 8 lambda expressions, so I'm not sure how to remove the entries correctly. Could somebody help me or explain what I have to do?

Here is the way I've tried doing it:

ArrayList<Integer> range10 = new ArrayList<Integer>();
    ArrayList<Integer> range15 = new ArrayList<Integer>();
    ArrayList<Integer> rangeMax = new ArrayList<Integer>();

for (int age = 16; age <= 100; age++){
        for (Entry<Integer, Partner> entry : dbMap.entrySet()){
            int key = entry.getKey();
            Partner person = entry.getValue();
            if (person.getAge() == alter && person.getAgeRange() == 10){
                range10.add(key);
                entry.setValue(null);
            }
            else if (person.getAge() == alter && person.getAgeRange() == 15){
                range15.add(key);
                entry.setValue(null);
                }
            else if (person.getAge() == age){
                rangeMax.add(key);
                entry.setValue(null);
                }
            dbMap.entrySet().removeIf(entries->entries.getValue().equals(null));

        }

And I get a java.lang.NullPointerException for it. I don't think this is a duplicate to asking what a NullPointerexception is, since I'm primarily asking how to use the removeif-function.

UsefulUserName
  • 555
  • 1
  • 4
  • 19

1 Answers1

35

You get that because you call .equals() on getValue() object, which is null, so it will not work. That happens here:

dbMap.entrySet().removeIf(entries->entries.getValue().equals(null));

What you have to do is this:

dbMap.entrySet().removeIf(entries->entries.getValue() == null);
Adnan Isajbegovic
  • 2,227
  • 17
  • 27
  • Thank you very much for you answer, This fixed my problem, although I now have a new one. I now have a `ConcurrentModificationException`. I thought `removeif` could be used, so that that exception would not be thrown. At least that is how i read this thread: [link](stackoverflow.com/a/29187813/2077574). Am I using this wrong? – UsefulUserName May 11 '16 at 12:02
  • @UsefulUserName If you have new question ask it in new thread (this way more people will see it and you get better chance of getting answer). Comments are not meant to be used as followup questions. – Pshemo May 11 '16 at 12:08
  • @Pshemo Alright, will do that. Thank you for that information. – UsefulUserName May 11 '16 at 12:32
  • Beware, ConcurrentHashMap is buggy in Java 8 "removeIf(filter) in ConcurrentHashMap removes entries for which filter is false" https://bugs.openjdk.java.net/browse/JDK-8078645. – buzz3791 Aug 23 '17 at 19:26