Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashmap with Streams in Java 8 Streams to collect value of Map

Let consider a hashmap

Map<Integer, List> id1 = new HashMap<Integer,List>(); 

I inserted some values into both hashmap.

For Example,

List<String> list1 = new ArrayList<String>();  list1.add("r1"); list1.add("r4");  List<String> list2 = new ArrayList<String>(); list2.add("r2"); list2.add("r5");  List<String> list3 = new ArrayList<String>(); list3.add("r3"); list3.add("r6");  id1.put(1,list1); id1.put(2,list2); id1.put(3,list3); id1.put(10,list2); id1.put(15,list3); 

Q1) Now I want to apply a filter condition on the key in hashmap and retrieve the corresponding value(List).

Eg: Here My query is key=1, and output should be 'list1'

I wrote

id1.entrySet().stream().filter( e -> e.getKey() == 1);              

But I don't know how to retrieve as a list as output of this stream operation.

Q2) Again I want to apply a filter condition on the key in hashmap and retrieve the corresponding list of lists.

Eg: Here My query is key=1%(i.e key can be 1,10,15), and output should be 'list1','list2','list3'(list of lists).

like image 781
Deepak Shajan Avatar asked Apr 14 '15 10:04

Deepak Shajan


People also ask

How do I collect a Stream map?

Method 1: Using Collectors.toMap() Function The Collectors. toMap() method takes two parameters as the input: KeyMapper: This function is used for extracting keys of the Map from stream value. ValueMapper: This function used for extracting the values of the map for the given key.

Can we use map Stream in Java 8?

Java 8 Stream's map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream. It simply used to convert Stream of one type to another. Let's see method signature of Stream's map method.


1 Answers

If you are sure you are going to get at most a single element that passed the filter (which is guaranteed by your filter), you can use findFirst :

Optional<List> o = id1.entrySet()                       .stream()                       .filter( e -> e.getKey() == 1)                       .map(Map.Entry::getValue)                       .findFirst(); 

In the general case, if the filter may match multiple Lists, you can collect them to a List of Lists :

List<List> list = id1.entrySet()                      .stream()                      .filter(.. some predicate...)                      .map(Map.Entry::getValue)                      .collect(Collectors.toList()); 
like image 75
Eran Avatar answered Sep 20 '22 16:09

Eran