我想同时执行两个流并生成第三个流作为前两个流的组合。假设我有以下两个流
Stream<String> a = Stream.of("f","b","z");
Stream<String> b = Stream.of("foo","bar","baz");
我想从这两个生成一个新的,相当于这个
Stream<String> c = Stream.of("f:foo","b:bar","z:baz");
到目前为止我发现的是Stream.concat或Stream.of
Stream<String> result = Stream.concat(a, b); or
Stream<String> result = Stream.of(a, b).flatMap(s -> s);
两者相互依存并对应于此处
Stream.of("f","b","z","foo","bar","baz");
到目前为止,我的解决方法是将两个流的元素分别收集到一个列表中,然后遍历两个列表以连接单个元素并将结果列表转换为一个流。strem api 中是否有更短的方法或现有函数可以同时在两个流上工作?
List<String> aList = a.collect(Collectors.toList());
List<String> bList = b.collect(Collectors.toList());
List<String> result = new ArrayList<>();
for(int i = 0; i< aList.size(); i++){
result.add(aList.get(i)+":"+bList.get(i));
}
Stream<String> cc = result.stream();
holdtom
扬帆大鱼
相关分类