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()
.
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
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.
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
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With