2596 views.
package com.learnbyexamples.streams;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/*
* Find number of keys which has 4 and 3 characters.
*/
public class E003_MapFilterStream {
public static void main(String[] args) {
//Simple map of strings
//{"Arun","Raja","Kumar","Ram","Siva"}
Map<String, String> names = new HashMap<>();
names.put("arun", "Arun Kumar");
names.put("raja", "Raja Ram");
names.put("kumar", "Dennis kumar");
names.put("ram", "Ram Kumar");
names.put("siva", "Sivakumar");
//Convert map entryset into Stream
Stream<Map.Entry<String, String>> namesStream = names.entrySet().stream();
//Filter 4 Char names gives new stream
//interface Predicate<T> which has single abstract method - boolean test(T t).
Stream<Map.Entry<String, String>> namesHas4Chrs = namesStream.filter(entry -> entry.getKey().length() == 4);
Map<String, String> filteredNames = namesHas4Chrs.collect(Collectors.toMap(e -> e.getKey() ,e -> e.getValue()));
System.out.println(filteredNames);
//If you want to do in single line.
Map<String, String> hasThreeChrs = names.entrySet().stream().filter(entry -> entry.getKey().length() == 3).collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()));
System.out.println(hasThreeChrs);
}
}