Java stream with method references for instanceof and class cast

Viewed 14009

Can I convert the following code using method reference?

List<Text> childrenToRemove = new ArrayList<>();

group.getChildren().stream()
    .filter(c -> c instanceof Text)
    .forEach(c -> childrenToRemove.add((Text)c));

Let me give 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 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 to convert an expression to a method reference?

2 Answers
Related