簡體   English   中英

如何從具有流的超類型列表中過濾掉特定子類型的不同對象

[英]How to filter out Distinct objects of a Particular subtype from a List of super type with Streams

我想創建一個 Java 流,它只收集屬於instanceofA元素,同時與x不同。

我正在使用 Java 8。

我一開始擁有的是C類實例的List

Class A extends B{
   int x;
}

Class B extends C{

}

Class C(){

}

但其他類也擴展了 C 類。

到目前為止我做了什么:

List<C> input = ...; 
List<C> result = input.stream()
    .filter(r -> r instanceof A)
    .collect(Collectors.toList());

然而,這對於第一部分來說效果很好。

但是,我想比較所有元素並獲取不同對象的List (按int x的值進行比較)。

首先,您應該覆蓋class A hashCodeequals來定義相等性。

一種方便的方法是使用Project lombok @EqualsAndHashCode提供的 @EqualsAndHashCode 從對象的字段生成hashCodeequals實現。

嘗試這個

@EqualsAndHashCode 
class A extends B {
   int x;
}

然后,只需簡單地使用stream().distinct()即可。

List<C> result = input.stream()
    .filter(r -> r instanceof A)
    .distinct()
    .collect(Collectors.toList());

參考https://projectlombok.org/features/EqualsAndHashCode

您可以定義一個期望目標類Class<T>實例的方法,以便從源列表中過濾掉C的任何子類型。

請注意,只有當每個子類都正確實現了equals/hashCode合同時,它才會起作用。

public static <T extends C> List<T> getItemsOfType(List<C> source,
                                                   Class<T> itemClass) {
    return source.stream()
        .filter(item -> itemClass.isAssignableFrom(item.getClass())) // ensures that this element can be safely casted to the target type
        .map(itemClass::cast) // casting to the type T
        .distinct()           // ensures uniqueness of elements according to `equals/hashCode` implementation of the type T
        .collect(Collectors.toList());
}

public static void main(String[] args) {
    List<C> input = List.of(new A(1), new D(), new A(3));
    List<A> result = getItemsOfType(input, A.class);

    System.out.println(result);
}

輸出:

[A{x=1}, A{x=3}]

暫無
暫無

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

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