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.
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.
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.
To remove all values from HashMap, use the clear() method.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With