Java如何随机获取List中的元素?实现代码一次搞定!

举报
赵KK日常技术记录 发表于 2023/09/22 23:38:28 2023/09/22
【摘要】 引言​在Java开发中,我们经常会遇到从一个List中随机获取元素的需求。可能是需要随机展示广告、抽奖活动、随机推荐等场景。本文将介绍几种简单而高效的方法来实现这个功能,并给出相应的代码示例。 方法一:使用Random类我们可以利用java.util.Random类来生成一个随机索引,然后根据该索引从List中获取对应的元素。下面是使用Random类实现随机获取元素的示例代码:import...

引言

在Java开发中,我们经常会遇到从一个List中随机获取元素的需求。可能是需要随机展示广告、抽奖活动、随机推荐等场景。本文将介绍几种简单而高效的方法来实现这个功能,并给出相应的代码示例。

方法一:使用Random类

我们可以利用java.util.Random类来生成一个随机索引,然后根据该索引从List中获取对应的元素。下面是使用Random类实现随机获取元素的示例代码:

import java.util.List;
import java.util.Random;

public class RandomElementSelector {

    public static <T> T getRandomElement(List<T> list) {
        if (list == null || list.isEmpty()) {
            throw new IllegalArgumentException("List cannot be null or empty");
        }

        Random random = new Random();
        int index = random.nextInt(list.size());

        return list.get(index);
    }

    public static void main(String[] args) {
        List<String> fruits = List.of("apple", "banana", "orange", "grape", "watermelon");
        String randomFruit = getRandomElement(fruits);
        System.out.println("Randomly selected fruit: " + randomFruit);
    }
}

以上代码首先检查了传入的List是否为空或者为null,如果是,则抛出异常。接着,我们创建一个java.util.Random对象,并使用nextInt()方法生成一个介于0到List大小之间(不包括List大小)的随机索引。最后,通过get()方法获取对应索引的元素。

这种方法简单直接,适用于大多数场景。

方法二:使用ThreadLocalRandom类

从Java 7开始,我们可以使用更高效的java.util.concurrent.ThreadLocalRandom类来生成随机数。这个类使用了线程本地变量,避免了多线程竞争情况下的性能问题。下面是使用ThreadLocalRandom类实现随机获取元素的示例代码:

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class RandomElementSelector {

    public static <T> T getRandomElement(List<T> list) {
        if (list == null || list.isEmpty()) {
            throw new IllegalArgumentException("List cannot be null or empty");
        }

        int index = ThreadLocalRandom.current().nextInt(list.size());

        return list.get(index);
    }

    public static void main(String[] args) {
        List<String> fruits = List.of("apple", "banana", "orange", "grape", "watermelon");
        String randomFruit = getRandomElement(fruits);
        System.out.println("Randomly selected fruit: " + randomFruit);
    }
}

这段代码与前面的示例非常相似,只是使用了ThreadLocalRandom.current().nextInt()方法来生成随机索引。

方法三:使用Collections.shuffle()方法

如果我们不关心每次获取元素时的顺序,而只是想随机排列整个List,然后按照顺序遍历,我们可以使用java.util.Collections.shuffle()方法。这个方法将会随机打乱List中的元素顺序。

以下是使用Collections.shuffle()方法实现随机获取元素的示例代码:

import java.util.Collections;
import java.util.List;

public class RandomElementSelector {

    public static <T> T getRandomElement(List<T> list) {
        if (list == null || list.isEmpty()) {
            throw new IllegalArgumentException("List cannot be null or empty");
        }

        Collections.shuffle(list);

        return list.get(0);
    }

    public static void main(String[] args) {
        List<String> fruits = List.of("apple", "banana", "orange", "grape", "watermelon");
        String randomFruit = getRandomElement(fruits);
        System.out.println("Randomly selected fruit: " + randomFruit);
    }
}

以上代码通过调用Collections.shuffle()方法来打乱List的元素顺序,然后直接返回第一个元素。

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。