Reputation: 197
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!
Upvotes: 5
Views: 4646
Reputation: 56433
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.
Upvotes: 4