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