的Person对象信息。
Stream.concat(streamOne, streamTwo).forEach(s->System.out.println(s));
}
}
运行效果完全一样:
宋远桥
苏星河
洪七公
张二狗
张天爱
张三
函数拼接与终结方法
在上述介绍的各种方法中,凡是返回值仍然为Stream
接口的为函数拼接方法,它们支持链式调用;而返回值不再为Stream
接口的为终结方法,不再支持链式调用。如下表所示:
方法名 |
方法作用 |
方法种类 |
是否支持链式调用 |
count |
统计个数 |
终结 |
否 |
forEach |
逐一处理 |
终结 |
否 |
filter |
过滤 |
函数拼接 |
是 |
limit |
取用前几个 |
函数拼接 |
是 |
skip |
跳过前几个 |
函数拼接 |
是 |
concat |
组合 |
函数拼接 |
是 |
Stream流中的结果到集合中
Stream流提供 collect方法,其参数需要一个 java.util.stream.Collector<T,A, R>接口对象来指定收集到哪 种集合中。java.util.stream.Collectors 类提供一些方法,可以作为 Collector`接口的实例:
- public static
Collector<T, ?, List
> toList():转换为 List集合。
- public static
Collector<T, ?, Set
> toSet():转换为 Set集合。
下面是这两个方法的基本使用代码
public class Test {
public static void main(String[] args) {
Stream<String> stream = Stream.of("aa", "bb", "cc");
//转换为list集合
List<String> list = stream.collect(Collectors.toList());
//转换为set集合
Set<String> set = stream.collect(Collectors.toSet());
//转换为ArrayList集合
ArrayList<String> arrayList = stream.collect(Collectors.toCollection(ArrayList::new));
//转换为HashSet集合
HashSet<String> hashSet = stream.collect(Collectors.toCollection(HashSet::new));
}
}
Stream流中的结果到数组中
Stream提供 toArray方法来将结果放到一个数组中,返回值类型是Object[]的:
Object[] toArray();
其使用场景如:
public class Test {
public static void main(String[] args) {
Stream<String> stream = Stream.of("aa", "bb", "cc");
Object[] objects = stream.toArray();
System.out.println(Arrays.toString(objects));
String[] strings = stream.toArray(String[]::new);
System.out.println(Arrays.toString(strings));
}
}