Filter a Map using Java 8 and Use Cases
Posted By : Shakil Pathan | 30-Apr-2019
Hi Guys,
In this blog, I am going to explain to you about different ways to filter Map entries in Java 8.
Before Java 8:
Map<Long, String> records = new HashMap<>();
records.put(1L, "first");
records.put(2L, "second");
String result = "";
for (Map.Entry<Long, String> entry : records.entrySet()) {
if("second".equals(entry.getValue())){
result = entry.getValue();
}
}
We have to use the entrySet method to loop over the keys and filter the entries.
With Java 8:
Map<Long, String> records = new HashMap<>();
records.put(1L, "first");
records.put(2L, "second");
String result = records.entrySet().stream()
.filter(entry -> "second".equals(entry.getValue()))
.map(entry -> entry.getValue())
.collect(Collectors.joining());
Map<Long, String> collect1 = records.entrySet().stream()
.filter(entry -> entry.getKey() == 2L)
.collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()));
Map<Long, String> collect2 = records.entrySet().stream()
.filter(entry -> entry.getKey() == 2L)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
Streams are a more declarative style or a more expressive style in Java 8. It may be considered better to declare your intent in code. We can convert a Map.entrySet() into a stream, followed by a filter() method and collect() method to collect it.
With Java 8 Predicate:
public static <K, V> Map<K, V> filterByValue(Map<K, V> map, Predicate<V> predicate) {
return map.entrySet()
.stream()
.filter(entry -> predicate.test(entry.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
public static void main(String[] args) {
Map<Long, String> records = new HashMap<>();
records.put(1L, "first");
records.put(2L, "second");
Map<Integer, String> filteredMap = filterByValue(records, entry -> (entry.contains("sec") && !entry.contains("firs")));
System.out.println(filteredMap);
}
The predicate is a functional interface and can, therefore, be used as the target assignment for a lambda expression or method reference.
Use cases:
Filter method returns a new stream that contains some of the elements from the original stream. It accepts the predicate to find which elements should be returned in the new stream and removes the rest.
In the functional style programming we don't bother with if statements, we just filter the stream and work only on the values we require. The whole idea of currents is to enable functional-style operations on the streams of elements. A stream is an abstraction, it is not a data structure. This is not a collection where you can store elements. The most important difference between a stream and a structure is that one stream does not hold data.
Hope it helps!
Thanks.
About Author
Shakil Pathan
Shakil is an experienced Groovy and Grails developer . He has also worked extensively on developing STB applications using NetGem .