原创

JAVA8系列教程-Boxed Stream

温馨提示:
本文最后更新于 2019年12月12日,已超过 1,603 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

Java 8中,如果要将对象流转换为collection,则可以使用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());

要转换原始的流,必须先box在他们的包装类的元素,然后收集它们。这种类型的流称为boxed stream

1. IntStream –stream of ints

将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

2. LongStream –stream of longs

将long流转换为Longs列表的示例

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 –stream of doubles

将double流转换为Doubles列表的示例

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]
正文到此结束
本文目录