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

后端 未结 6 1897
悲&欢浪女
悲&欢浪女 2021-01-30 19:59

Let consider a hashmap

Map id1 = new HashMap();

I inserted some values into both hashmap.

For

6条回答
  •  無奈伤痛
    2021-01-30 20:22

    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 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 = id1.entrySet()
                         .stream()
                         .filter(.. some predicate...)
                         .map(Map.Entry::getValue)
                         .collect(Collectors.toList());
    

提交回复
热议问题