两种主要方式。
- 用途
Random#nextInt(int)
:List<Foo> list = createItSomehow();
Random random = new Random();
Foo foo = list.get(random.nextInt(list.size()));
但是,不能保证连续的
n调用返回唯一的元素。
- 用途
Collections#shuffle()
:List<Foo> list = createItSomehow();
Collections.shuffle(list);
Foo foo = list.get(0);
它使您能够
n通过递增索引来获取唯一元素(假设列表本身包含唯一元素)。
如果您想知道是否有Java 8
Stream方法;不,没有内置的。没有
Comparator#randomOrder()标准API中的功能(还可以吗?)。您可以在满足严格
Comparator合同的情况下尝试以下操作(尽管分发情况非常糟糕):
List<Foo> list = createItSomehow();int random = new Random().nextInt();Foo foo = list.stream().sorted(Comparator.comparingInt(o -> System.identityHashCode(o) ^ random)).findFirst().get();
最好
Collections#shuffle()改用。



