java8 中Collectors.toMap解決鍵重復問題


例子:

 Map<Integer, List<String>> manGroupIdsMap = manualEntries.stream().collect(Collectors.toMap(ManualEntry::getId, manualEntry -> Arrays.stream(StringUtils.split(manualEntry.getGroupInsIds(), ","))
                .filter(StringUtils::isNotEmpty).collect(toList()), (List<String> value1, List<String> value2) -> value2));

 

分析:

toMap接口:

 public static <T, K, U>
    Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
                                    Function<? super T, ? extends U> valueMapper,
                                    BinaryOperator<U> mergeFunction) {
        return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
    }

參數:

第一個參數為要組成的Map的Key,例如上面例子中用ManualEntry的Id做key;

第二個參數為map的value,例如例子中要生成的value為manualEntry.getGroupInsIds()分割后組成的List的合集

第三個參數則為key重復時處理方法:例子中的處理方式是如果重復,使用value2,即覆蓋,也可以做其他處理


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM