Casting – Java 8 – filtering collections with external parameters
•
Java
I have an animal map containing specific successors
MyBaSEObjectAnimalMap.values().stream(). filter(x -> x instanceof Dog). map(x -> (Dog) x). toArray(Dog[]::new);
Is there any way to abstract this?
I want to implement a private method with the following signature:
filterMapByType(Map<String,Animal> map,Class<T extends Animal> type)
Or something like that
Solution
You can provide an intfunction to call toArray, so you can get an array of type t instead of an array of objects
public static <T extends Animal> T[] filterMapByType(Map<String,Class<T> type,IntFunction<T[]> generator) { return map.values() .stream() .filter(type::isinstance) .map(type::cast) .toArray(generator); }
Give an example of a telephone call:
Dog[] dogs = filterMapByType(map,Dog.class,Dog[]::new);
Dog []: new is equivalent to length – > new dog [length], that is, a function that takes an int as a parameter and returns an array of type dog with the size of length
If you can return to a list, you can use collect(toList()); instead of. ToArray (generator);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码