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,即覆盖,也可以做其他处理

猜你喜欢

转载自www.cnblogs.com/leiqian-xaut/p/12447293.html
今日推荐