Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using removeif on a hashmap [duplicate]

Tags:

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.

like image 209
UsefulUserName Avatar asked May 11 '16 11:05

UsefulUserName


People also ask

Can HashMap have duplicate keys?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

How do you remove an element from a HashMap while iterating?

While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry. getKey() method. If the key matches, remove the entry of that iteration from the HashMap using remove() method.

How remove all values from HashMap in Java?

To remove all values from HashMap, use the clear() method.


1 Answers

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);
like image 62
Adnan Isajbegovic Avatar answered Jan 02 '23 07:01

Adnan Isajbegovic