在 Java 8 中,如果要将对象流转换为集合,则可以使用Collector
类中的静态方法之一。
//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());
要转换原始流,必须首先将包装类中的元素装箱,然后收集它们。 这种类型的流称为装箱流。
1. IntStream
– 整数流
示例将int
流转换为Integer
列表。
//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
2. LongStream
– 长整数流
示例将long
流转换为Long
列表。
List<Long> longs = LongStream.of(1l,2l,3l,4l,5l)
.boxed()
.collect(Collectors.toList());
System.out.println(longs);
Output:
[1, 2, 3, 4, 5]
3. DoubleStream
– 双精度流
示例将double
流转换为Double
列表。
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]
在 Java 流 API 中与装箱流或原始类型有关的评论部分中,向我提出您的问题。
学习愉快!