1. 程式人生 > 程式設計 >如何在java 8 map中使用stream

如何在java 8 map中使用stream

簡介

Map是java中非常常用的一個集合型別,我們通常也需要去遍歷Map去獲取某些值,java 8引入了Stream的概念,那麼我們怎麼在Map中使用Stream呢?

基本概念

Map有key,value還有表示key,value整體的Entry。

建立一個Map:

Map<String,String> someMap = new HashMap<>();

獲取Map的entrySet:

Set<Map.Entry<String,String>> entries = someMap.entrySet();

獲取map的key:

Set<String> keySet = someMap.keySet();


獲取map的value:

Collection<String> values = someMap.values();

上面我們可以看到有這樣幾個集合:Map,Set,Collection。

除了Map沒有stream,其他兩個都有stream方法:

Stream<Map.Entry<String,String>> entriesStream = entries.stream();
Stream<String> valuesStream = values.stream();
Stream<String> keysStream = keySet.stream();

我們可以通過其他幾個stream來遍歷map。

使用Stream獲取map的key

我們先給map新增幾個值:

someMap.put("jack","20");
someMap.put("bill","35");

上面我們添加了name和age欄位。

如果我們想查詢age=20的key,則可以這樣做:

Optional<String> optionalName = someMap.entrySet().stream()
        .filter(e -> "20".equals(e.getValue()))
        .map(Map.Entry::getKey)
        .findFirst();
    log.info(optionalName.get());

因為返回的是Optional,如果值不存在的情況下,我們也可以處理:

optionalName = someMap.entrySet().stream()
        .filter(e -> "Non ages".equals(e.getValue()))
        .map(Map.Entry::getKey).findFirst();

    log.info("{}",optionalName.isPresent());

上面的例子我們通過呼叫isPresent來判斷age是否存在。

如果有多個值,我們可以這樣寫:

someMap.put("alice","20");
    List<String> listnames = someMap.entrySet().stream()
        .filter(e -> e.getValue().equals("20"))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

    log.info("{}",listnames);

上面我們呼叫了collect(Collectors.toList())將值轉成了List。

使用stream獲取map的value

上面我們獲取的map的key,同樣的我們也可以獲取map的value:

List<String> listAges = someMap.entrySet().stream()
        .filter(e -> e.getKey().equals("alice"))
        .map(Map.Entry::getValue)
        .collect(Collectors.toList());

    log.info("{}",listAges);

上面我們匹配了key值是alice的value。

總結

Stream是一個非常強大的功能,通過和map相結合,我們可以更加簡單的操作map物件。

本文的例子https://github.com/ddean2009/learn-java-streams/tree/master/stream-formap

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。