Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java 8 streams filter list of objects to determine whether they are instanceof specific class and distinct by property at the same time

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading