簡體   English   中英

屬性GS集合Java中的不同對象

[英]Distinct objects from property GS collections Java

假設我有一個具有兩個屬性的客戶列表(GS集合):id和age,我想對屬性id應用不同的過濾器

 FastList<Customer> customers ...
 customers.distinct( ) //Hey here there's no overload to provide a custom comparator!

distinct()toSet()之間的distinct()在於distinct()將保留原始列表的順序,但是兩者都依賴於使用equals()hashCode()的默認對象相等性。

方法toSortedSet()需要一個Comparator ,並且toSortedSetBy()允許您僅傳入Function 兩者都應該為您工作。 這是使用Java 8的toSortedSetBy()外觀。

FastList<Customer> customers = ...;
MutableSortedSet<Customer> sortedSet = customers.toSortedSetBy(Customer::getId);

使用SortedSetIterable有兩個缺點。 首先是算法是O(n log n)而不是O(n)。 第二個原因是,如果SortedSetIterable的equals方法與比較器不一致(Customer.equals()不會將兩個Customer相等,即使它們具有相同的ID), SortedSetIterable行為也會很奇怪。

第二種方法是使用UnifiedSetWithHashingStrategy

FastList<Customer> customers = FastList.newListWith(c1, c2, c3);
UnifiedSetWithHashingStrategy<Customer> set =
  new UnifiedSetWithHashingStrategy<>(HashingStrategies.fromIntFunction(Customer::getId));
set.addAll(customers);

這需要O(n)的時間,但是您會失去順序。 GS Collections沒有采用HashingStrategydistinct()形式,但是您可以自己編寫。

public static <T> FastList<T> distinct(
        FastList<T> fastList, 
        HashingStrategy<T> hashingStrategy)
{
  MutableSet<T> seenSoFar = 
          UnifiedSetWithHashingStrategy.newSet(hashingStrategy);
  FastList<T> targetCollection = FastList.newList();
  for (int i = 0; i < fastList.size(); i++)
  {
    if (seenSoFar.add(fastList.get(i)))
    {
      targetCollection.add(fastList.get(i));
    }
  }
  return targetCollection;
}

然后您像這樣使用它。

distinct(customers, HashingStrategies.fromIntFunction(Customer::getId));

暫無
暫無

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

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