2015-06-29 93 views
3

我應該做的是通過stream.generate創建一個隨機數的ArrayList。下面的代碼是我嘗試將它保存到一個ArrayList中,但它是「object」類型的。我想我必須首先將它映射爲int,但我不知道如何。代碼現在不起作用。將生成的流保存到ArrayList中

public ArrayList<Integer> createRandomList(ArrayList<Integer> list, int amount) { 
    ArrayList<Integer> a = Arrays.asList(Stream.generate(new Supplier<Integer>() { 
        @Override 
        public Integer get() { 
         Random rnd = new Random(); 
         return rnd.nextInt(100000); 
        } 
       }).limit(amount).mapToInt.toArray()); 
} 

回答

3

你可以使用一個收集器:

return Stream.generate (() -> new Random().nextInt(100000)) 
      .limit(amount) 
      .collect (Collectors.toList()); 

這將產生一個List<Integer>雖然不一定是ArrayList<Integer>

它會更有意義,雖然創建一個單一的隨機實例:

final Random rnd = new Random(); 
return Stream.generate (() -> rnd.nextInt(100000)) 
      .limit(amount) 
      .collect (Collectors.toList()); 
+2

好的,收集操作到底做了什麼? – taclight

+1

@taclight它使用提供的收集器收集流的元素。 'Collectors.toList()'是一個收集器,它創建一個List實例,將所有Stream元素添加到它,並返回該List。 – Eran

+1

它如何知道列表中的元素必須是哪種類型? – taclight

2

您可以使用直接從使用ints(...)Random對象創建整數流,使用boxed()盒子裏,用收集來存儲結果:

return new Random().ints(amount, 0, 100000) 
        .boxed() 
        .collect(Collectors.toCollection(ArrayList::new)); 
+1

...並且如果OP堅持以後有一個'ArrayList','.collect(Collectors.toCollection(ArrayList :: new))'。也許你想補充一點。 – Holger

+1

@霍爾謝謝 – taclight

+0

@霍爾:更新,謝謝。 –

相關問題