Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java filter list to generic type T

Tags:

java

How can I do the following (this doesn't compile):

<T> List<T> getElementsOf() {
    return list.stream()
            .filter(x -> x instanceof T)
            .map(x -> (T) x)
            .collect(toList());
}

What would be example of usage? Ideally, it should be like obj.<Derived>getElementsOf().

like image 221
demi Avatar asked Dec 06 '16 06:12

demi


People also ask

How to use generic list interface in Java?

Java has provided generic support in List interface. Syntax List<T> list = new ArrayList<T>(); Where. list − object of List interface. T − The generic type parameter passed during list declaration. Description. The T is a type parameter passed to the generic interface List and its implemenation class ArrayList. Example

What are generics in Java?

Before generics, we can store any type of objects in the collection, i.e., non-generic. Now generics force the java programmer to store a specific type of objects. There are mainly 3 advantages of generics.

What is the generic type parameter passed during list declaration in Java?

Java has provided generic support in List interface. Syntax List<T> list = new ArrayList<T>(); Where list − object of List interface. T − The generic type parameter passed during list declaration. Description The T is a type parameter

What is T in Java list declaration?

T − The generic type parameter passed during list declaration. The T is a type parameter passed to the generic interface List and its implemenation class ArrayList. Create the following java program using any editor of your choice.


2 Answers

Although the other answer pretty much does the job, here's a better one:

<T> List<T> getElementsOf(Class<T> clazz) {
    return list.stream()
            .filter(clazz::isInstance)
            .map(clazz::cast)
            .collect(toList());
}

Notice that the clazz::isInstance thingy. Instead of comparing the two classes, it uses the isInstance method. According to the docs, this is equivalent to instanceof, which is what you wanted in the first place.

This method is the dynamic equivalent of the Java language instanceof operator.

like image 83
Sweeper Avatar answered Sep 30 '22 04:09

Sweeper


I got the following:

<T> List<T> getChildrenOf(Class<T> clazz) {
    return children.stream()
            .filter(node -> node.getClass() == clazz)
            .map(node -> clazz.<T>cast(node))
            .collect(toList());
}

List<Mesh> nameNodes = b.getChildrenOf(Mesh.class);
like image 39
demi Avatar answered Sep 30 '22 04:09

demi