How to randomly pick an element from an array

前端 未结 12 857
逝去的感伤
逝去的感伤 2020-11-22 16:48

I am looking for solution to pick number randomly from an integer array.

For example I have an array new int[]{1,2,3}, how can I pick a number randomly?

12条回答
  •  感动是毒
    2020-11-22 17:03

    package io.github.baijifeilong.tmp;
    
    import java.util.concurrent.ThreadLocalRandom;
    import java.util.stream.Stream;
    
    /**
     * Created by BaiJiFeiLong@gmail.com at 2019/1/3 下午7:34
     */
    public class Bar {
        public static void main(String[] args) {
            Stream.generate(() -> null).limit(10).forEach($ -> {
                System.out.println(new String[]{"hello", "world"}[ThreadLocalRandom.current().nextInt(2)]);
            });
        }
    }
    

提交回复
热议问题