簡體   English   中英

如何通過更新重復項的值來合並兩個集合

[英]how to merge two collections by updating a value on duplicates

我有這個課:

class A{
 int count=0;


 //equals and hashCode implemented
}

創建兩個集合:

Collection<A>  collection1;//something
Collection<A>  collection2;//something

連接集合:

Stream.concat(collection1.stream(), collection2.stream())
                //do something here???
                .distinct()
                .sorted(new Comparator<A>() {
                  @Override
                  public int compare(A o1, A o2) {

                     return new Integer(o1.count).compareTo(new Integer(o2.count));
                  }
                })
                .collect(Collectors.toList());

我想合並這兩個列表,如果有重復項,我想更新整數count; 上面的代碼完全消除了重復項

例如,假設我們在collection1和collection2中都獲得了一個相等的對象(o1.equals(o2) == true) 一個有count=10 ,另一個有count=20我想收集一組不同的對象,使該對象的count=30

有辦法嗎?

您無法使用當前的方法來執行此操作,而是可以使用toMap收集器:

Stream.concat(collection1.stream(), collection2.stream())
       .collect(Collectors.toMap(Function.identity(),Function.identity(),
       (left, right) -> {
          left.setCount(left.getCount() + right.getCount());
          return left;
       })).values()
         .stream()
         .sorted(Comparator.comparingInt(A::getCount))
         .collect(Collectors.toList());

這使用Stream.concatcollection1collection2合並為一個Stream<A>

然后,我們調用toMap收集器,其中第一個Function.identity()選擇源元素作為鍵,即A ,第二個Function.identity()也選擇源元素作為值; 再次是A ,因此在這一點上,您可以將數據可視化為Map<A, A>

函數(left, right) -> { ... }被稱為合並函數,在這里,如果兩個給定的對象相等,那么我們說取第一個元素的計數並取第二個元素的計數,將它們加在一起,然后將新值分配回我們要保留的元素之一,然后丟棄另一個。

因為您已經覆蓋了equalshashcode ,所以我們不需要顯式調用它,而是將 調用equals方法來確定兩個給定的對象是否相等。

一旦將元素收集到Map<A, A> ,然后調用values()方法來檢索Collection<A> ,這使我們能夠使用stream()方法從該stream()創建一個流使我們能夠使用sorted方法對流元素進行排序,最后使用toList收集器將其收集到List<A>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM