結局のところ、私はストリームの結合には興味がありませんが、これらすべてのストリームの各要素を処理した結果の結合に興味があります。
ストリームの結合は厄介であることが判明する可能性がありますが(このスレッドのため)、処理結果の結合はかなり簡単です。
解決する鍵は、独自のコレクターを作成し、新しいコレクターのサプライヤー関数が毎回同じもの(新しいコレクションではない)を返すようにすることです。以下のコードは、このアプローチを示しています。
package scratchpad;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Stream;
public class CombineStreams {
public CombineStreams() {
super();
}
public static void main(String[] args) {
List<String> resultList = new ArrayList<>();
Collector<String, List<String>, List<String>> collector = Collector.of(
() -> resultList,
(list, item) -> {
list.add(item);
},
(llist, rlist) -> {
llist.addAll(rlist);
return llist;
}
);
String searchString = "Wil";
System.out.println("After processing first stream\n"
+ createFirstStream().filter(name -> name.contains(searchString)).collect(collector));
System.out.println();
System.out.println("After processing second stream\n"
+ createSecondStream().filter(name -> name.contains(searchString)).collect(collector));
System.out.println();
System.out.println("After processing third stream\n"
+ createThirdStream().filter(name -> name.contains(searchString)).collect(collector));
System.out.println();
}
private static Stream<String> createFirstStream() {
return Arrays.asList(
"William Shakespeare",
"Emily Dickinson",
"H. P. Lovecraft",
"Arthur Conan Doyle",
"Leo Tolstoy",
"Edgar Allan Poe",
"Robert Ervin Howard",
"Rabindranath Tagore",
"Rudyard Kipling",
"Seneca",
"John Donne",
"Sarah Williams",
"Oscar Wilde",
"Catullus",
"Alfred Tennyson",
"William Blake",
"Charles Dickens",
"John Keats",
"Theodor Herzl"
).stream();
}
private static Stream<String> createSecondStream() {
return Arrays.asList(
"Percy Bysshe Shelley",
"Ernest Hemingway",
"Barack Obama",
"Anton Chekhov",
"Henry Wadsworth Longfellow",
"Arthur Schopenhauer",
"Jacob De Haas",
"George Gordon Byron",
"Jack London",
"Robert Frost",
"Abraham Lincoln",
"O. Henry",
"Ovid",
"Robert Louis Stevenson",
"John Masefield",
"James Joyce",
"Clark Ashton Smith",
"Aristotle",
"William Wordsworth",
"Jane Austen"
).stream();
}
private static Stream<String> createThirdStream() {
return Arrays.asList(
"Niccolò Machiavelli",
"Lewis Carroll",
"Robert Burns",
"Edgar Rice Burroughs",
"Plato",
"John Milton",
"Ralph Waldo Emerson",
"Margaret Thatcher",
"Sylvie d'Avigdor",
"Marcus Tullius Cicero",
"Banjo Paterson",
"Woodrow Wilson",
"Walt Whitman",
"Theodore Roosevelt",
"Agatha Christie",
"Ambrose Bierce",
"Nikola Tesla",
"Franz Kafka"
).stream();
}
}