Randomly select an item from a list

2019-01-03 06:46发布

How can I randomly select an item from a list in Java? e.g. I have

List<String> list = new ArrayList<String>();
list.add("One");
list.add("Two");

etc.... How can I randomly select from this list using the

Random myRandomizer = new Random();

2条回答
唯我独甜
2楼-- · 2019-01-03 07:34

Something like this?

Random randomizer = new Random();
String random = list.get(randomizer.nextInt(list.size()));
查看更多
可以哭但决不认输i
3楼-- · 2019-01-03 07:34

Clean Code:

List<String> list = new ArrayList<String>();
list.add("One");
list.add("Two");
String random = list.get(new Random().nextInt(list.size()));
查看更多
登录 后发表回答