【弄nèng - 化繁为简】Java8 List<Object>转Map<Integer,List< Object >>

211 阅读1分钟

一. Collectors.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);
    }

有三个参数,还有个默认参数 参数含义:

- keyMapper:Key 的映射函数
   
- valueMapper:Value 的映射函数
   
- mergeFunction:当 Key 冲突时,调用的处理方法
   
- mapSupplier:Map 构造器,在需要返回特定的 Map 时使用

二. 事例

输入

	public static void main(String[] args) {
        List<TestEntity> testList = Lists.newArrayList(
                new TestEntity().setId(1).setName("张三"),
                new TestEntity().setId(1).setName("李四"), // Key 相同
                new TestEntity().setId(2).setName("王五")
        );

        Map<Integer, String> map = testList.stream()
                .collect(Collectors.toMap(TestEntity::getId, TestEntity::getName, (n1, n2) -> n1 + n2));
        System.out.println("map:" + map);
    }

输出 在这里插入图片描述

三. List转Map<Integer,List< Object >>

输入

    public static void main(String[] args) {
        List<TestEntity> testList = Lists.newArrayList(
                new TestEntity().setId(1).setName("张三"),
                new TestEntity().setId(1).setName("李四"), // Key 相同
                new TestEntity().setId(2).setName("王五")
        );

        Map<Integer, String> map = testList.stream()
                .collect(Collectors.toMap(TestEntity::getId, TestEntity::getName, (n1, n2) -> n1 + n2));
        System.out.println("map:" + map);

        Map<Integer, List<TestEntity>> mapList = testList.stream()
                .collect(Collectors.toMap(TestEntity::getId, item -> {
                    List<TestEntity> list = Lists.newArrayList();
                    list.add(item);
                    return list;
                }, (n1, n2) -> {
                    n1.addAll(n2);
                    return n1;
                }));
        System.out.println("map:" + mapList);
    }

输出 在这里插入图片描述