带有instanceof和类cast的方法引用的Java流

Gab*_*Chu 10 java java-8 java-stream method-reference

我可以使用方法参考转换以下代码吗?

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

group.getChildren().stream()
    .filter(c -> c instanceof Text)
    .forEach(c -> childrenToRemove.add((Text)c));
Run Code Online (Sandbox Code Playgroud)

让我举一个例子来说明我的意思,假设我们有

myList
    .stream()
    .filter(s -> s.startsWith("c"))
    .map(String::toUpperCase)
    .sorted()
    .forEach(elem -> System.out.println(elem));
Run Code Online (Sandbox Code Playgroud)

使用方法引用它可以写成(最后一行)

myList
    .stream()
    .filter(s -> s.startsWith("c"))
    .map(String::toUpperCase)
    .sorted()
    .forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)

将表达式转换为方法引用的规则是什么?

ste*_*fen 23

是的,您可以使用以下方法参考:

.filter(Text.class::isInstance)
.map(Text.class::cast)
.forEach(childrenToRemove::add);
Run Code Online (Sandbox Code Playgroud)

而不是为-各加,你可以收集流项目有Collectors.toSet():

Set<Text> childrenToRemove = group.getChildren()
    // ...
    .collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)

toList()如果您需要维护儿童的顺序,请使用.

如果签名匹配,则可以使用方法引用替换lambda表达式:

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
Run Code Online (Sandbox Code Playgroud)