java8中stream的提供了一個拼接流的方法Stream.concat,可以將兩個stream拼接成一個stream, 保持了兩個stream中的元素順序。
那么如果我們需要對多個集合中的元素拼接成一個stream來統(tǒng)一處理,可以怎么做呢?
比如有三個Collection<String> c1, c2, c3.
方法一,使用Stream.concat方法來拼接,可以使用一個for循環(huán)來處理。
private static Stream<String>?concat1(List<Collection<String>> collections) {
Stream result = Stream.empty();
for (Collection<String> strings : collections) {
? ? ? ? ? ? ? result = Stream.concat(result, ?strings.stream());
}
return ? result;
}
方法二,使用flatMap方法,將集合變成stream, 再壓平
private static Stream<String>?concat2(List<Collection<String>> collections) {
return ?collections.stream()
? ? ? ? ? ?.flatMap(Collection::stream);
}
對于不同集合類型的數據,如何做成一個統(tǒng)一的流?還是可以使用flatMap方法來做
方法三:
private static Stream<String>?concat3(List<String> s1,String[] s2, Set<String> s3) {
return ?Stream.of(s1.stream(), Arrays.stream(s2), s3.stream())
? ? ? ? ? ?.flatMap(Function.identity());
}
方法三和方法二相比,可以使用不同類型的集合類型來拼接流,方法二在擁有共同基類的情況下使用會顯得簡潔很多。