Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Saturday, April 22, 2023

How to Remove a Key, Value, or Entry from HashMap in Java 8 - Example Tutorial

In the last article, I have shown how to remove key/value pairs from a map in Java-based upon some conditions like removing all entries where values are greater than some values. I have told you that you must use the Iterator's remove() method for removing mapping while iteration to avoid ConcurrentModificationException, but that's not required anymore in Java 8. From JDK 8 onwards, you can selectively remove mapping without iterating over Map. The JDK 8 API has added several new methods to existing interfaces e.g. java.util.Collection, java.util.Map, Comparator, etc because the interface can now contain concrete methods in the form of static and default methods.

One such method is the removeIf() method of the Collection class which allows you to remove entries based upon some condition or predicate.

It takes a lambda expression, which can be used to supply the predicate you want. For example, you can rewrite the above code in Java 8 as shown in the following example:

Since here we need to compare values, I have called the values() method which returns a collection of values.

Once you got that, you can simply call removeIf() method which takes a Predicate. Just pass the condition you want to check for removing values from the map.

Btw, if you are not familiar with the new functional programming API added on Java 8 then I suggest you first go through a comprehensive and up-to-date Java course. If you need recommendations, you can also check this list of the best Java Functional Programming courses. It covers all important topics for Java developers and is also regularly updated to the latest Java versions. 

How to delete a Key, Value, or Entry from a HashMap using the removeIf() function

Btw, If you want to test keys from the Map for removing the mapping, you can just call the keySet() or entrySet() methods and apply the removeIf() call as shown below:

How to Remove a key value pair or Entry from HashMap in Java 8

Also here is more code to copy-paste and try yourself:
System.out.println("map before removing values: " + priceMap);
priceMap.entrySet().removeIf( e -> e.getValue()
                               .compareTo(Double.valueOf(39.00)) > 0);
System.out.println("map after removing values: " + priceMap);

map before removing values: {Java SE 8 for Really Impatient=31.99,
 Head First Design Pattern=39.05, Java Concurrency In Practice=30.67,
 Effective Java=41.79, Head First Java=29.02}
map after removing values: {Java SE 8 for Really Impatient=31.99,
 Java Concurrency In Practice=30.67, Head First Java=29.02}

You can see how easy it is to remove key-value pairs based upon some condition in Java. You can use the newly added removeIf() method from Collection to achieve that.

So, all we did on our whole program, you can simply do it in just one line in Java 8. That's the beauty of Java 8. I strongly suggest you read a good book on Java 8 like Java 8 in Action to learn more about such useful tricks.

How to delete a key value pair or Entry from HashMap in Java 8

That's all about how to remove a key-value pair from a HashMap in Java 8. You can see that now you can safely remove entries based upon some conditions without iterating over them, hence you don't need to use the Iterator's remove() method to avoid ConcurrentModificationException in Java while removing entries from HashMap.

Related Java 8 Tutorials

If you are interested in learning more about the new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:
  • 5 Books to Learn Java 8 from Scratch (books)
  • What is the default method in Java 8? (example)
  • Top 5 Courses to learn Java 8 Lambda and Stream (courses)
  • How to join String in Java 8 (example)
  • How to use filter() method in Java 8 (tutorial)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • How to use Stream class in Java 8 (tutorial)
  • How to convert List to Map in Java 8 (solution)
  • Difference between abstract class and interface in Java 8? (answer)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • How to use peek() method in Java 8 (example)
  • How to sort the map by keys in Java 8? (example)
  • How to sort the may by values in Java 8? (example)
  • 10 examples of Optionals in Java 8? (example)

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or suggestions then please drop a comment.

P. S. - If you are new to Java 8 features, particularly lambda expression and Stream API, and looking for a free online course to improve your functional programming skills then you can also join Java 8 Functional Programming: Lambda Expressions Quickly (FREE) course on Udemy. It's completely free and more than 27,000 students have already benefited from it.


Anonymous said...

( d -> d.compareTo ) What does d means here?

Anonymous said...

d means a variable pointing to elements in the collection

javin paul said...

Yes, that's correct, in lambda expression you can use a variable, you don't need to define their type e.g. String or Integer, or Comparable, Java compiler will automatically infer it.

In priceMap.values().removeIf( d -> d.compareTo(Double.valueOf(39.00)) > 0);

the values() method return a collection of Values and d is a local variable to hold current element of Collection.

Deepak A L said...

Can you post the complete working java example for removeIf without hardcoding 39.00

Post a Comment