最终,我对合并流不感兴趣,但对获得处理所有这些流的每个元素的合并结果不感兴趣。
虽然合并流可能被证明很麻烦(因此该线程),但是合并它们的处理结果是相当容易的。
解决的关键是创建自己的收集器,并确保新收集器的供应商功能每次都返回相同的收集(不是新收集器),下面的代码说明了这种方法。
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();
}
}