5

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!

5
  • yes. car.getColors.remove(null); Commented Jan 2, 2018 at 22:17
  • What is difficult about this? for (Car car : listOfCars) { car.colors.remove(null); }. Commented Jan 2, 2018 at 22:19
  • I was confused a bit with the multiple iterations. Thanks for your answer. Commented Jan 2, 2018 at 22:30
  • What you really need is a solution that prevents the null from getting in there in the first place. Commented Jan 2, 2018 at 23:17
  • @EJP, I have a usecase where we use the Thrift API to serialize/deserialize objects to Database(Cassandra). Using this API requires that each time you make any changes to the model, you need to regenerate the java classes using their utility(.exe). In scenarios if we miss to regenerate the java classes, it ends up deserializing objects containing map with null keys. Thats where I had been looking for a solution. Commented Jan 3, 2018 at 19:10

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Why wouldn't you just use Map.remove directly, which avoids iterating over the entire map?
@LouisWasserman true, guess I overlooked the problem at hand.
Thanks! I was also checking to see how I could remove the additional iteration. The answer had been quite straight forward. Should have checked again before posting it.
Iterating over a map can have a point if you don't know whether the map supports null, i.e. remove(null) and containsKey(null) could both throw. But then map.keySet().removeIf(Objects::isNull) still is simpler than operating with entrySet().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.