簡體   English   中英

獲取 Map 中最內層的值作為 `Map 中的列表<string, list<map<string,map<string,string> &gt;&gt;&gt;` Java</string,>

[英]Get inner most values in the Map as a List in `Map<String, List<Map<String,Map<String,String>>>>` Java

我需要將最里面的 map 中的值作為Map<String, List<Map<String,Map<String,String>>>>中的列表。

除了每個,我們可以使用流來實現它嗎?

Stream#flatMap 返回所有元素的所有值的 Stream:

List<String> converted = yourComplexStructure.values().stream()
    .flatMap(List::stream)
    .map(Map::values)
    .flatMap(Collection::stream())
    .map(Map::values)
    .flatMap(Collection::stream()))
    .collect(Collectors.toList());

It takes the values of your structure as a Stream, maps it to a Stream with all elements of each List, maps it to a Stream with all values of the Maps, creates a Stream with all values of the most inner maps and collects it.


請注意,它與其他答案基本相同(我們同時編寫了它),但我更改了此答案,以便它不需要 lambdas 但使用方法引用。

也許

    List<String> keys = map.values().stream() // get the first list
            .flatMap(List::stream) //flatten the list
            .flatMap(mapOfMap -> mapOfMap.values().stream()) //get the list of all values
            .flatMap(mapOfMap -> mapOfMap.keySet().stream()) //get the keys
            .collect(Collectors.toList());

正如@dan1st 所指出的, flatMap是這里成功的關鍵。

要獲取值,您只需更改最里面的 flatMap:

    List<String> values = map.values().stream() // get the first list
            .flatMap(List::stream) //flatten the list
            .flatMap(mapOfMap -> mapOfMap.values().stream()) //get the list of all values
            .flatMap(mapOfMap -> mapOfMap.values().stream()) //get the values
            .collect(Collectors.toList());

要過濾鍵:

List<String> values = map.values().stream() // get the first list
                .flatMap(List::stream) //flatten the list
                .flatMap(mapOfMap -> mapOfMap.values().stream()) //get the list of all values
                .flatMap(mapOfMap -> mapOfMap.entrySet().stream()) //get the entries (key -> value)
                .filter(entry -> entry.getKey().equals("somekey")) //filter here
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM