Using removeif on a hashmap

24,842

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);
Share:
24,842
UsefulUserName
Author by

UsefulUserName

Updated on July 09, 2022

Comments

  • UsefulUserName
    UsefulUserName almost 2 years

    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
    UsefulUserName about 8 years
    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?
  • Pshemo
    Pshemo about 8 years
    @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.
  • UsefulUserName
    UsefulUserName about 8 years
    @Pshemo Alright, will do that. Thank you for that information.
  • buzz3791
    buzz3791 almost 7 years
    Beware, ConcurrentHashMap is buggy in Java 8 "removeIf(filter) in ConcurrentHashMap removes entries for which filter is false" bugs.openjdk.java.net/browse/JDK-8078645.