場景
使用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]