Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eliminate null key from hashmap which is present inside an arraylist

Tags:

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!

like image 661
user1347244 Avatar asked Jan 02 '18 22:01

user1347244


People also ask

Can you remove a key from HashMap?

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.

What if key is null in HashMap?

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.


1 Answers

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.

like image 175
Ousmane D. Avatar answered Sep 23 '22 13:09

Ousmane D.