LongStream对象转化为List对象
场景
使用Random类获取伪随机数时,发现longs方法获得了LongStream对象,而我想将其转换为List对象,因为不熟悉流式编程所以特此记录。
语法与说明
<R> R collect(Supplier<R> supplier, ObjLongConsumer<R> accumulator, BiConsumer<R,R> combiner)
对流对象做转换。
例子
将LongStream对象转换为List
Random random = new Random();
LongStream longs = random.longs(10, 0L, 3000L);
ArrayList<Long> collect = longs.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
LongStream longs1 = random.longs(3, 3000L, 10000L);
ArrayList<Long> collect1 = longs1.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
collect.addAll(collect1);
System.out.println(collect);
结果:
[2500, 1400, 1289, 184, 179, 875, 800, 2580, 1608, 318, 3844, 3359, 8699]