关于java8:Java-8-StreamBox

Java 8 StreamBox Java 8的装箱流

1. 什么是 盒装流(Boxed Stream)

在java8 中,如果咱们想把一个对象流转变成一个汇合,咱们能够应用Collectors 类中的一个静态方法

List<String> strings = Stream.of("how", "to", "do", "in", "java")
                    .collect(Collectors.toList());

然而对于根本类型的数据缺失不适合的

// 编译谬误
IntStream.of(1,2,3,4,5)
//                .collect(Collectors.toList());

如果想不呈现编译不出错,咱们必须打包这个元素,而后再汇合中收集被包装的对象,这种类型的流称为 盒装流

2. 将 int 流转换成 Integer 汇合
List<Integer> ints = IntStream.of(1,2,3,4,5)
                .boxed()
                .collect(Collectors.toList());
         
System.out.println(ints);
 
//间接对流进行操作,获取最大值
Optional<Integer> max = IntStream.of(1,2,3,4,5)
                .boxed()
                .max(Integer::compareTo);
 
System.out.println(max)

3. LongStream

将 long 类型的流转换成成 Long 类型

List<Long> longs = LongStream.of(1l,2l,3l,4l,5l)
                .boxed()
                .collect(Collectors.toList());

4. doubleStream
List<Double> doubles = DoubleStream.of(1d,2d,3d,4d,5d)
                .boxed()
                .collect(Collectors.toList());

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理