Shuffle a list of integers with Java 8 Streams API

后端 未结 8 1146
别那么骄傲
别那么骄傲 2020-11-28 09:34

I tried to translate the following line of Scala to Java 8 using the Streams API:

// Scala
util.Random.shuffle((1 to 24).toList)

To write t

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 10:28

    Here you go:

    List integers =
        IntStream.range(1, 10)                      // <-- creates a stream of ints
            .boxed()                                // <-- converts them to Integers
            .collect(Collectors.toList());          // <-- collects the values to a list
    
    Collections.shuffle(integers);
    
    System.out.println(integers);
    

    Prints:

    [8, 1, 5, 3, 4, 2, 6, 9, 7]
    

提交回复
热议问题