收集Stream流中的结果
1. 将流中数据收集到集合中
Stream流提供 collect 方法,其参数需要一个 java.util.stream.Collector<T,A, R> 接口对象来指定收集到哪
种集合中。java.util.stream.Collectors 类提供一些方法,可以作为 Collector接口的实例:
public static <T> Collector<T, ?, List<T>> toList() :转换为 List 集合。
public static <T> Collector<T, ?, Set<T>> toSet() :转换为 Set 集合。
基本使用:
@Test
public void testStreamToCollection() {
Stream<String> stream = Stream.of("aa", "bb", "cc", "bb");
// 将流中数据收集到集合中
List<String> list = stream.collect(Collectors.toList());
System.out.println("list = " + list);
Set<String> set = stream.collect(Collectors.toSet());
System.out.println("set = " + set);
// 收集到指定的集合中
ArrayList<String> arrayList = stream.collect(Collectors.toCollection(ArrayList::new));
System.out.println("arrayList = " + arrayList);
HashSet<String> hashSet = stream.collect(Collectors.toCollection(HashSet::new));
System.out.println("hashSet = " + hashSet);
}
2. 将流中的数据收集到数组中
Stream提供 toArray 方法来将结果放到一个数组中,返回值类型是Object[]的:
Object[] toArray();
<A> A[] toArray(IntFunction<A[]> generator);
// 其中,IntFunction接口有一个抽象方法R
R apply(int value);
基本使用:
@Test
public void testStreamToArray() {
Stream<String> stream = Stream.of("aa", "bb", "cc");
// 转成Object数组不方便
// Object[] objects = stream.toArray();
// for (Object o : objects) {
// System.out.println("o = " + o);
// }
// String[]
String[] strings = stream.toArray(String[]::new);
for (String string : strings) {
System.out.println("string = " + string + ", 长度: " + string.length());
}
}
// 输出结果:
string = aa, 长度: 2
string = bb, 长度: 2
string = cc, 长度: 2
3. 对流中数据进行聚合计算
当我们使用Stream流处理数据后,可以像数据库的聚合函数一样对某个字段进行操作。比如获取最大值,获取最小值,求总和,平均值,统计数量。
java.util.stream.Collectors 类提供一些方法,可以实现上述操作。
3.1 maxBy、minBy
通过Collectors中的maxBy和minBy方法,可以获取流中的数据的最大值和最小值,并将最后的结果返回。
public static <T> Collector<T, ?, Optional<T>>
maxBy(Comparator<? super T> comparator