2017-05-24 32 views
3

可以使用方法引用转换以下代码吗?具有instanceof和class cast方法引用的Java流

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

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

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

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

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

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

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

回答

9

是的,你可以使用这些方法的引用:

.filter(Text.class::isInstance) 
    .map(Text.class::cast) 
    .forEach(childrenToRemove::add); 

代替的for-each加,你可以收集流项目与Collectors.toSet()

Set<Text> childrenToRemove = group.getChildren() 
    // ... 
    .collect(Collectors.toSet()); 

使用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 
0

我想是的,它是可能的,像这样

group.getChildren() 
    .filter(Text.class::isInstance) 
    .map(Text.class::cast) 
    .collect(Collectors.toCollection(() -> childrenToRemove));