2017-05-24 37 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));