您可以在以下實現你forSome
功能方法:
public static <T> T forSome(T c, Predicate<T> condition, Consumer<T> extraBehaviour) {
if (condition.test(c)) {
extraBehaviour.accept(c);
}
return c;
}
比你可以使用地圖運營商注入流這樣的:
List<Cube> revised = cubes.stream().filter(p)
.map(c -> f(c))
.map(c -> forSome(c, Cube::prop, cube -> cube.addComment("my comment 2")))
.collect(Collectors.toList());
只給使用的另一個例子中,我們可以採取下面的例子:
class StudentExam {
private final String studentName;
private final List<Character> answers;
private boolean passed = false;
StudentExam(String studentName, List<Character> answers) {
this.studentName = studentName;
this.answers = answers;
}
public void markAsPassed() {
this.passed = true;
}
public boolean isPassed() {
return passed;
}
public Character getAnswer(int index) {
return answers.get(index);
}
public String getStudentName() {
return studentName;
}
}
List<StudentExam> results = asList(
new StudentExam("John", asList(new Character[] {'A', 'B'})),
new StudentExam("Andy", asList(new Character[] {'A', 'C'})),
new StudentExam("Mary", asList(new Character[] {'B', 'B'})),
new StudentExam("Jane", asList(new Character[] {'C', 'D'}))
);
現在我們可以,如果正確答案是「A」和「B」比我們可以通過對象流和設置考試的適當狀態。
results.stream()
.map(examResult -> forSome(
examResult,
er -> er.getAnswer(0).equals('A') || er.getAnswer(1).equals('B'),
StudentExam::markAsPassed))
.forEach(studentExam ->
studentExam.getStudentName() + " passed: " + studentExam.isPassed()));
打印:
- 約翰:通過真實
- 安迪:通過真實
- 瑪麗:通過真實
- 簡:通過假
是Optional.ifPresent接受? – VGR
@VGR正是我的想法:) – Eugene
[Collectors.partitioningBy](https://stackoverflow.com/a/30110890/3688648)可能會幫助,如果你想通過'立方體::道具'「發球」你的流# – Felk