我们开发过程中经常遇到把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);
    Map<String, B> bMap2 = convertList2Map(bList, (B b) -> b.getB1() + b.getB2());
    System.out.println("----------bMap1------------");
    System.out.println(bMap1);
}

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


求平安
15 声望0 粉丝

家人平平安安。


引用和评论

0 条评论