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

后端 未结 6 1837
悲&欢浪女
悲&欢浪女 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:19

    What you need to do is create a Stream out of the Map's .entrySet():

    // Map --> Set> --> Stream>
    map.entrySet().stream()
    

    From the on, you can .filter() over these entries. For instance:

    // Stream> --> Stream>
    .filter(entry -> entry.getKey() == 1)
    

    And to obtain the values from it you .map():

    // Stream> --> Stream
    .map(Map.Entry::getValue)
    

    Finally, you need to collect into a List:

    // Stream --> List
    .collect(Collectors.toList())
    

    If you have only one entry, use this instead (NOTE: this code assumes that there is a value; otherwise, use .orElse(); see the javadoc of Optional for more details):

    // Stream --> Optional --> V
    .findFirst().get()
    

提交回复
热议问题