網頁

2020/9/24

Java 8 lambda combine two list with duplicate key

Java 8 lambda 合併兩個List,並排除具有相同key的物件。

Order為範例List中裝載的元素,id為key。

Order

public class Order {
    
    private long id; // key
    private long amount;
    
    Order(long id, long amount) {
        this.id = id;
        this.amount = amount;
    }

    @Override
    public String toString() {
        return String.format("id=%s, amount=%s", id, amount);
    }

    // getters and setters...
}

使用Stream.concat()合併兩個ListStream。然後用filter()搭配TreeSet排除key重複的物件,

例如下面合併list1list2,並以Order.id做為比較是否重覆,如果相同則以list1為主。

Main

public class Main {

    public static void main(String[] args) {

        List<Order> list1 = Arrays.asList(
                new Order(1, 10),
                new Order(2, 100));

        List<Order> list2 = Arrays.asList(
                new Order(1, 9),
                new Order(2, 99),
                new Order(3, 1000),
                new Order(4, 10000));

//        TreeSet<Order> treeSet = new TreeSet<>(Comparator.comparing(Order::getId));
//        List<Order> combinedList = Stream.concat(
//                list1.stream(), list2.stream())
//                .filter(treeSet::add)
//                .collect(Collectors.toList());

        List<Order> combinedList = Stream.concat(
                list1.stream(), list2.stream())
                .filter(new TreeSet<>(Comparator.comparing(Order::getId))::add)
                .collect(Collectors.toList());

        combinedList.forEach(System.out::println);
    }

}

印出結果。

id=1, amount=10
id=2, amount=100
id=3, amount=1000
id=4, amount=10000


沒有留言:

張貼留言