How to remove entries from java map based on values

Remove all entries in map by value

Java Map is a data structure that holds key->value pairs. In this article we will see how to delete all entries in the map by map values.

Using removeAll

removeAll() takes one argument a collection. And entries matching the passed collection will be removed from the original map
Using removeAll
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
map.put(6, "five");

newline("Original Map");
map.values().removeAll(Collections.singleton("five"));

newline("After removing values = five");
map.forEach( (a,b) -> {
	System.out.println(a + " -> " + b);
});
Output of above program.
Original Map
1 -> one
2 -> two
3 -> three
4 -> four
5 -> five
6 -> five
7 -> five

After removing values = five
1 -> one
2 -> two
3 -> three
4 -> four

Using removeIf

removeIf
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
map.put(6, "five");

newline("Original Map");

//remove entries where value = five
map.values().removeIf("five"::equals);

newline("After removing values = five");
map.forEach( (a,b) -> {
	System.out.println(a + " -> " + b);
});
Output of above program.
Original Map
1 -> one
2 -> two
3 -> three
4 -> four
5 -> five
6 -> five
7 -> five

After removing values = five
1 -> one
2 -> two
3 -> three
4 -> four

No comments :

Post a Comment

Please leave your message queries or suggetions.