Skip to content
Advertisement

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

Let consider a hashmap

JavaScript

I inserted some values into both hashmap.

For Example,

JavaScript

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

JavaScript

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).

Advertisement

Answer

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 :

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement