簡體   English   中英

Java 8流HashMap <String, ArrayList<String> &gt;到SortedMap <String, Integer>

[英]Java 8 stream HashMap<String, ArrayList<String>> to SortedMap<String, Integer>

我有HashMap<String, ArrayList<String>> professions ,我想創建一個SortedMap<String, Integer> ,其中第一個條目是與hashmap的第一個條目相同的字符串,第二個條目是一個等於第一個映射中ArrayList的大小對應於該字符串。 我還希望sortedMap按第一個條目(字符串)排序。

我嘗試了以下方法:

professions.entrySet().stream()
            .collect(Collectors.groupingBy(e -> e.getKey(), TreeMap::new,
                    Collectors.mapping(e -> e.getValue().size()));

Eclipse告訴我The method mapping(Function<? super T,? extends U>, Collector<? super U,A,R>) in the type Collectors is not applicable for the arguments ((<no type> e) -> {})和也The method getValue() is undefined for the type T

我不確定我的解決方案是否完全錯誤,或者只是不能推斷類型的eclipse。

您正在尋找toMap收集器而不是groupingBy

Map<String, Integer> resultSet = 
     professions.entrySet()
                .stream()
                .collect(Collectors.toMap(Map.Entry::getKey,
                        e -> e.getValue().size(),
                        (left, right) -> left, TreeMap::new));

暫無
暫無

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

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