博客 / 詳情

返回

List<T> 轉 Map<K, T>通用方法

我們開發過程中經常遇到把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);
}

通過比對兩種轉換方式的打印結果,結論是通用的轉換方法是可行的。效率上沒有提高,就是代碼會簡短一點,碼農不用記那麼多代碼了!

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.