How to generate random array of ints using Stream API Java 8?

后端 未结 4 1090
别那么骄傲
别那么骄傲 2020-12-15 16:59

I am trying to generate random array of integers using new Stream API in Java 8. But I haven\'t understood this API clearly yet. So I need help. Here is my code.

         


        
相关标签:
4条回答
  • 2020-12-15 17:27

    To generate random numbers from range 0 to 350, limiting the result to 10, and collect as a List. Later it could be typecasted.

    However, There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned.

    List<Object> numbers =  new Random().ints(0,350).limit(10).boxed().collect(Collectors.toList());
    

    and to get thearray of int use

    int[] numbers =  new Random().ints(0,350).limit(10).toArray();
    
    0 讨论(0)
  • 2020-12-15 17:29

    You can do it using ThreadLocalRandom.

    int[] randInts = ThreadLocalRandom.current().ints().limit(100).toArray();
    
    0 讨论(0)
  • 2020-12-15 17:36

    There's no reason to boxed(). Just receive the Stream as an int[].

    int[] array = intStream.limit(limit).toArray();
    
    0 讨论(0)
  • 2020-12-15 17:53

    If you want primitive int values, do not call IntStream::boxed as that produces Integer objects by boxing.

    Simply use Random::ints which returns an IntStream:

    int[] array = new Random().ints(size, lowBound, highBound).toArray();
    
    0 讨论(0)
提交回复
热议问题