Using removeif on a hashmap

时间:2016-05-11 11:30:18

标签: java hashmap

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.

1 个答案:

答案 0 :(得分:17)

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);