Java 从集合中获取随机元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21092086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:31:14  来源:igfitidea点击:

Get Random Element from Collection

java

提问by Secret

I have a Collection<Obj>how do I get a random Objfrom it?

我有一个Collection<Obj>如何从中获得随机数Obj

I've checked the docsand there doesn't seem to be a way, since iterator is the only way to access the collection. Do I have to iterate over it to get a random object!?

我检查了文档,似乎没有办法,因为迭代器是访问集合的唯一方法。我是否必须迭代它才能获得一个随机对象!?

采纳答案by Peter Lawrey

The most efficient it to only iterate as far as you need.

最有效的方法是仅根据需要进行迭代。

public static <T> T random(Collection<T> coll) {
    int num = (int) (Math.random() * coll.size());
    for(T t: coll) if (--num < 0) return t;
    throw new AssertionError();
}

回答by A Paul

User Collections.shuffle(list);. Then you can just get the first element. It will be random.

用户Collections.shuffle(list);. 然后你就可以得到第一个元素。这将是随机的。

or you can also do this

或者你也可以这样做

int size = list.size();
int item = new Random().nextInt(size); 
list.get(item )

回答by Autocrab

private Object getRandomObject(Collection from) {
   Random rnd = new Random();
   int i = rnd.nextInt(from.size());
   return from.toArray()[i];
}

回答by Maurice Perry

Several options (by order of efficiency):

几个选项(按效率排序):

  • use a List instead of a Collection,
  • generate a random index with random.nextInt(collection.size()), get an iterator and iterate,
  • generate a random index with random.nextInt(collection.size()), convert the collection into an array with toArray(), and index that array.
  • 使用列表而不是集合,
  • 用 random.nextInt(collection.size()) 生成一个随机索引,得到一个迭代器并迭代,
  • 使用 random.nextInt(collection.size()) 生成随机索引,使用 toArray() 将集合转换为数组,并索引该数组。

回答by Witold Kaczurba

Using Lambdas you can do this quite quickly and handle the case when Collection is empty.

使用 Lambdas,您可以非常快速地完成此操作并处理 Collection 为空的情况。

public static <E> Optional<E> getRandom (Collection<E> e) {

    return e.stream()
            .skip((int) (e.size() * Math.random()))
            .findFirst();
}

回答by RKumsher

If you don't mind a 3rd party library, the Utilslibrary has a IterableUtilsthat has a randomFrom(Iterable iterable) method that will take a Collection and return a random element from it

如果您不介意第 3 方库,Utils库有一个IterableUtils,它有一个 randomFrom(Iterable iterable) 方法,该方法将获取一个集合并从中返回一个随机元素

Collection<Object> collection = ....;
Object random = IterableUtils.randomFrom(collection);

It is in the Maven Central Repository at:

它位于 Maven 中央存储库中:

<dependency>
  <groupId>com.github.rkumsher</groupId>
  <artifactId>utils</artifactId>
  <version>1.3</version>
</dependency>

回答by Ernest Sadykov

Solution using Google Guava Iterables.get()method:

使用谷歌番石榴Iterables.get()方法的解决方案:

private <T> T getRandomObject(Collection<T> from) {
   Random rnd = new Random();
   int i = rnd.nextInt(from.size());
   return Iterables.get(from, i);
}

If you want to handle empty collections as well, the method with defaultValuemay be used: Iterables.get(from, i, null)

如果您还想处理空集合,可以使用with 方法defaultValueIterables.get(from, i, null)