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

推荐阅读

AI文本 OCR识别最佳实践

AI Gamma一键生成PPT工具直达链接

玩转cloud Studio 在线编码神器

玩转 GPU AI绘画、AI讲话、翻译,GPU点亮AI想象空间

资源分享

AI绘画 stable diffusion Midjourney 官方GPT文档 AIGC百科全书资料收集

史上最全文档AI绘画stablediffusion资料分享

AI绘画关于SD,MJ,GPT,SDXL百科全书

「java、python面试题」来自UC网盘app分享,打开手机app,额外获得1T空间
https://drive.uc.cn/s/2aeb6c2dcedd4
AIGC资料包
https://drive.uc.cn/s/6077fc42116d4
https://pan.xunlei.com/s/VN_qC7kwpKFgKLto4KgP4Do_A1?pwd=7kbv#

引言
在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的元素顺序,然后直接返回第一个元素。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值