文
章
目
录
章
目
录
在Java中,装箱流(Boxed Stream)是包装类实例的流,用于模拟原始数据类型的流。
1.什么是装箱流?
Java Stream API的设计目的是与对象一起工作,类似于Collections API。流不会像对象一样处理原始类型。
在Stream API中,原始数据类型的流可以通过以下3个类表示:
- IntStream
- LongStream
- DoubleStream
要将原始数据类型的流转换为对象流,这些类提供了boxed()方法,该方法返回由给定流中的元素组成的流,每个元素都装箱到相应包装类的对象中。
Stream<Integer> stream = IntStream.of(1, 2, 3, 4, 5).boxed();
Stream<Long> stream1 = LongStream.of(1, 2, 3, 4, 5).boxed();
Stream<Double> stream2 = DoubleStream.of(1.0, 2.0, 3.0, 4.0, 5.0).boxed();
2. 为什么需要boxed装箱操作
如果不将流项装箱,我们无法对它们执行常规流操作。例如,我们不能直接将int值收集到List中。
//编译报错
/*List<Integer> list = IntStream.of(1,2,3,4,5)
.collect(Collectors.toList());*/
为了使上述收集过程起作用,我们必须首先将流元素装箱。