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

Deepak Shajan picture Deepak Shajan · Apr 14, 2015 · Viewed 177.6k times · Source

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

Answer

Eran picture Eran · Apr 14, 2015

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());