[英]How extract sorted list of distinct integers from a Set of objects using Java streams?
[英]How to filter out Distinct objects of a Particular subtype from a List of super type with Streams
我想創建一個 Java 流,它只收集屬於instanceof
類A
元素,同時與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
hashCode
和equals
來定義相等性。
一種方便的方法是使用Project lombok
@EqualsAndHashCode
提供的 @EqualsAndHashCode 從對象的字段生成hashCode
和equals
實現。
嘗試這個
@EqualsAndHashCode
class A extends B {
int x;
}
然后,只需簡單地使用stream().distinct()
即可。
List<C> result = input.stream()
.filter(r -> r instanceof A)
.distinct()
.collect(Collectors.toList());
您可以定義一個期望目標類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.