目录
一般在Java中使用stream有三步:第一步生成stream;第二步对stream进行转换;第三步聚合操作得到想要的结果。
在java 8中,如果要将对象流转换为集合,那么可以使用collectors类中的一个静态方法。
//It works perfect !!
List<String> strings = Stream.of("how", "to", "do", "in", "java")
.collect(Collectors.toList());
但是,同一个进程对基本类型流不起作用。
//Compilation Error !!
IntStream.of(1,2,3,4,5)
.collect(Collectors.toList());
若要转换基本类型流,必须首先将元素打包到其包装类中,然后收集它们。这种类型的流称为装箱流。
将int流转换为Integers集合的示例。
//Get the collection and later convert to stream to process elements
List<Integer> ints = IntStream.of(1,2,3,4,5)
.boxed()
.collect(Collectors.toList());
System.out.println(ints);
//Stream operations directly
Optional<Integer> max = IntStream.of(1,2,3,4,5)
.boxed()
.max(Integer::compareTo);
System.out.println(max);
程序输出:
[1, 2, 3, 4, 5]
5
将长流转换为长整型集合的示例。
List<Long> longs = LongStream.of(1l,2l,3l,4l,5l)
.boxed()
.collect(Collectors.toList());
System.out.println(longs);
Output:
[1, 2, 3, 4, 5]
将双精度流转换为双精度集合的示例。
List<Double> doubles = DoubleStream.of(1d,2d,3d,4d,5d)
.boxed()
.collect(Collectors.toList());
System.out.println(doubles);
Output:
[1.0, 2.0, 3.0, 4.0, 5.0]
Stream主要用于对象类型的集合,但JDK还提供了基本类型的Stream,这让我们可以直接使用IntStream,而不是Stream
4.1算术操作(求最大值最小直)
我们经常会用求最小值、最大值、和、平均数等常用的操作,下面我们介绍一下算术的基本操作:
int[] integers = new int[]{20, 98, 12, 7, 35};
int min = Arrays.stream(integers)
.min()
.getAsInt();
我们使用Arrays的stream()方法创建了一个int类型的stream,通过min()求出最小值,然后通过getAsInt()返回int的值。
又或者可以通过另一种方法实现:
int max = IntStream.of(23, 32, 98, 1, 3)
.max()
.getAsInt();
4.2?算术操作(求和与平均直)
方法同上
int sum = IntStream.of(3, 2, 1).sum();
double avg = IntStream.of(73, 232, 232, 1)
.average()
.getAsDouble();
4.3 range()和rangeClosed()的区别
int sum1 = IntStream.range(1, 10)
.sum();//return 45
int sum2 = IntStream.rangeClosed(1, 10)
.sum();//return 55
显而易见:range()是exclusive最后一个值的,rangeClosed()是inclusive的。
4.4 遍历操作:
IntStream.rangeClosed(1, 5)
.forEach(System.out::println);
并行操作:
IntStream.rangeClosed(1, 5)
.parallel()
.forEach(System.out::println);
有时我们需要将基本类型转化为对应的包装类型,就需要用到自动装箱操作:
List<Integer> evenInts = IntStream.rangeClosed(1, 100)
.filter(num -> num % 2 == 0)
.boxed()
.collect(Collectors.toList());
同样,我们也可以将包装类型转化为基本类型:
sum = Arrays.asList(1,2,3,4)
.stream()
.mapToInt( i -> i)
.sum();
如有疑问欢迎来加入QQ群交流:758799436
原文:https://www.cnblogs.com/huzidashu/p/11697767.html