I am looking for an optimized solution to remove null
keys from a HashMap
. This HashMap is present inside an ArrayList
. Please find the example below.
public class Car {
String year;
String model;
Map<String,String> colors;
}
List<Car> listOfCars = new ArrayList<Car>();
Sample of the colors map could be like this:
{
red(1),
blue(2),
green(3),
black(4),
null(5)
}
I need a solution to iterate over the listOfCars
, get the map of colors and remove the null
key from that. Trying to see any other options in Java8 rather than using an Iterator.
Thanks!
remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Parameters: The method takes one parameter key whose mapping is to be removed from the Map.
HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. This class makes no guarantees as to the order of the map.
Considering a map cannot contain duplicate keys, we can, therefore, say that each Map
instance of a Car
instance will only ever have at most one entry with a null
key.
The solution using the Java-8 forEach
construct is:
listOfCars.forEach(e -> e.getColors().remove(null));
Although it can be done with a for
loop or an enhanced for
loop as well.
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