关于java8:ListT-转-MapK-T通用方法

30次阅读

共计 2193 个字符,预计需要花费 6 分钟才能阅读完成。

咱们开发过程中常常遇到把 List<T> 转成 map 对象的场景,同时须要对 key 值雷同的对象做个合并,lambda 曾经做得很好了。
定义两个实体类别离命名为 A、B。

@Data
class A {
    private String a1;
    private String a2;
    private String a3;

    public A(String a1, String a2, String a3) {
        this.a1 = a1;
        this.a2 = a2;
        this.a3 = a3;
    }
}

@Data
class B {
    private String b1;
    private String b2;
    private String b3;

    public B(String b1, String b2, String b3) {
        this.b1 = b1;
        this.b2 = b2;
        this.b3 = b3;
    }
}

lambda 转换代码:

@Test
public void test1() {List<A> aList = new ArrayList<>();
    aList.add(new A("a1", "a21", "a3"));
    aList.add(new A("a1", "a22", "a3"));
    aList.add(new A("a11", "a23", "a3"));
    aList.add(new A("a11", "a24", "a3"));
    aList.add(new A("a21", "a25", "a3"));
    System.out.println(aList);
    Map<String, A> tagMap = CollectionUtils.isEmpty(aList) ? new HashMap<>() :
            aList.stream().collect(Collectors.toMap(A::getA1, a -> a, (k1, k2) -> k1));
    System.out.println("----------------------");
    System.out.println(tagMap);
    System.out.println("----------------------");
}

能不能把转换的过程提取成公共办法呢?
我做了个尝试,公共的转换方法如下:

public <K, T> Map<K, T> convertList2Map(List<T> list, Function<T, K> function) {Map<K, T> map = CollectionUtils.isEmpty(list) ? new HashMap<>() :
            list.stream().collect(Collectors.toMap(function, a -> a, (k1, k2) -> k1));

    return map;
}

上面是验证过程, 别离应用空集合与有数据的汇合做比照:

@Test
public void test1() {List<A> aList = new ArrayList<>();
    System.out.println(aList);
    Map<String, A> tagMap = CollectionUtils.isEmpty(aList) ? new HashMap<>() :
            aList.stream().collect(Collectors.toMap(A::getA1, a -> a, (k1, k2) -> k1));
    System.out.println("----------------------");
    System.out.println(tagMap);
    System.out.println("----------------------");
    Map<String, A> tagMap1 = convertList2Map(aList, A::getA1);;
    System.out.println(tagMap1);

    List<B> bList = new ArrayList<>();
    bList.add(new B("b1", "a21", "a3"));
    bList.add(new B("b1", "a22", "a3"));
    bList.add(new B("b11", "a23", "a3"));
    bList.add(new B("b11", "a24", "a3"));
    bList.add(new B("b21", "a25", "a3"));
    System.out.println("----------------------");
    System.out.println(bList);
    Map<String, B> bMap = CollectionUtils.isEmpty(bList) ? new HashMap<>() :
            bList.stream().collect(Collectors.toMap(B::getB1, a -> a, (k1, k2) -> k1));
    System.out.println("----------bMap------------");
    System.out.println(bMap);
    Map<String, B> bMap1 = convertList2Map(bList, B::getB1);
    System.out.println("----------bMap1------------");
    System.out.println(bMap1);
}

通过比对两种转换形式的打印后果,论断是通用的转换方法是可行的。效率上没有进步,就是代码会简短一点,码农不必记那么多代码了!

正文完
 0