I would like to create a java stream that will collect only elements that are instanceof class A and at the same time are distinct by x. I am using java 8. What I have in the beggining is an List of objects of class C.
Class A extends B{
int x;
}
Class B extends C{
}
Class C(){
}
but other classes also extend class C.
What I did so far:
List<C> input = ...;
List<C> result = input.stream().filter(r -> r instanceof A).collect(Collectors.toList());
And this works fine however for the first part, however now I would like to also compare all elements and get List of distinct objects(compare by value of int x).
>Solution :
You can define a method that would expect an intance of Class
in order to filter out any subtype of A
from the source list.
That would work only if equals/hashCode
contract was properly implemented by each subclass.
public static <T extends A> List<T> getItemsOfType(List<A> source, Class<T> itemClass) {
return source.stream()
.filter(item -> item instanceof T)
.map(itemClass::cast)
.distinct()
.collect(Collectors.toList());
}
public static void main(String[] args) {
List<A> input = // initializing the input list
List<C> result = getItemsOfType(input, C.class);
}