你可以看看下面的。它演示了只打印過濾對象或包含過濾對象的列表的方法。這裏的過濾邏輯是保留有偶數的org.apache.commons.lang3.tuple.Pair
。
public static void main(String[] args) {
// print raw output
getListObservable().subscribe(System.out::println);
// print the objects post filtering
getListObservable().flatMap(v -> Observable.from(v)).filter(p -> p.getRight()%2==0).subscribe(System.out::println);
// print the list refined with only filtered objects
getListObservable().flatMap(v -> Observable.just(v.stream().filter(p -> p.getRight()%2==0).collect(Collectors.toList()))).subscribe(System.out::println);
}
private static Observable<List<Pair<Integer, Integer>>> getListObservable() {
return Observable.create(subscriber -> {
for(int i=0; i<5; i++){
List<Pair<Integer, Integer>> list = new ArrayList<>();
for(int j=0; j<5; j++){
list.add(Pair.of(i, j));
}
subscriber.onNext(list);
}
});
}
輸出與可觀察到的內容:
[(0,0), (0,1), (0,2), (0,3), (0,4)]
[(1,0), (1,1), (1,2), (1,3), (1,4)]
[(2,0), (2,1), (2,2), (2,3), (2,4)]
[(3,0), (3,1), (3,2), (3,3), (3,4)]
[(4,0), (4,1), (4,2), (4,3), (4,4)]
輸出只包含過濾的對象:
(0,0)
(0,2)
(0,4)
(1,0)
(1,2)
(1,4)
(2,0)
(2,2)
(2,4)
(3,0)
(3,2)
(3,4)
(4,0)
(4,2)
(4,4)
輸出以包含僅含有過濾的對象的列表。
[(0,0), (0,2), (0,4)]
[(1,0), (1,2), (1,4)]
[(2,0), (2,2), (2,4)]
[(3,0), (3,2), (3,4)]
[(4,0), (4,2), (4,4)]
請問您能否將lambda擴展到Java 8之前的代碼?將真的有助於這樣看待 – Bootstrapper
不適用於Flowable –