【问题标题】:Java 8: Random selection of List using Random.LongStream()Java 8:使用 Random.LongStream() 随机选择列表
【发布时间】:2021-12-04 18:41:13
【问题描述】:

如果给它一个 Random.IntStream(),有没有办法从流中随机选择项目(不重复)?

谢谢

【问题讨论】:

  • 是否要多次选择同一个元素?
  • 你问了两个问题。请编辑您的问题,以便您只问一个问题。见how to ask questions
  • 类似Random.ints(0, items.size()).distinct().map(n -> items.get(n));?
  • @Bohemian 第二个问题在哪里?我只看到一个。他问了一个问题,并解释了他为什么问这个问题。
  • @marstran 不,有两个基本上不相关的问题 - 每个句子一个。第一个问题涉及从Random.IntStream() 中获取不重复的“选择”(大小有限?未说明)元素。第二个处理从 1000 个元素的 ArrayList 中随机选择 10 个元素(没有提到重复)。

标签: java random collections java-stream


【解决方案1】:

假设您有一个包含 1000 个 Foo 对象的数组列表,并且您需要从该列表中随机选择 10 个元素,则可以使用 Random.ints(int origin, int bound) 在列表中获取“无限”随机索引流,然后通过索引选择需要的元素:

List<Foo> largeFooList = List.of(...); // 1000+ Foo objects

List<Foo> lucky10 = new Random() // or ThreadLocalRandom.current()
    .ints(0, largeFooList.size())
    .distinct() // ensure all the ids are different
    .limit(10)
    .mapToObj(largeFooList::get)
    .collect(Collectors.toList());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    相关资源
    最近更新 更多