Java stream with method references for instanceof instance and class
Is it possible to transform the following code with a method reference?
List<Text> childrenToRemove = new ArrayList<>();
group.getChildren().stream()
.filter(c -> c instanceof Text)
.forEach(c -> childrenToRemove.add((Text)c));
Let me give you an example to illustrate what I mean, suppose we have
myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(elem -> System.out.println(elem));
using a method reference it can be written as (last line)
myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
What are the rules for converting an expression to a method reference?
+3
source to share
2 answers
Yes, you can use these method links:
.filter(Text.class::isInstance)
.map(Text.class::cast)
.forEach(childrenToRemove::add);
Instead of for-each-add, you can collect stream elements with Collectors.toSet()
:
Set<Text> childrenToRemove = group.getChildren()
// ...
.collect(Collectors.toSet());
Use toList()
if you need to keep the kids tidy.
You can replace lambda expressions with method references if the signatures match using these rules:
ContainingClass::staticMethodName // method reference to a static method
containingObject::instanceMethodName // method reference to an instance method
ContainingType::methodName // method reference to an instance method
ClassName::new // method reference to a constructor
+9
source to share