让我们说:
String[] fruitsArray = new String[] {"apple", "orange", "pear", "banana", "cherry", "blueberry", "papaya", "litchi"};
如何从这个数组中随机选择四个元素而不重复?
示例结果将是["orange", "pear","blueberry","litchi"]
,而像["apple", "orange","orange","papaya"]
这样的结果是不可接受的。
与使用Collections::shuffle
对阵列或集合进行简单的混洗相比,生成不可重复的数字并不是一件容易的事。
final String[] fruitArray = new String[]{"apple", "orange", "pear", "banana",
"cherry", "blueberry", "papaya", "litchi"};
// SHUFFLE
final List<String> fruitList = Arrays.asList(fruitArray);
Collections.shuffle(fruitList);
// TEST IT
fruitList.stream()
.limit(4) // sets the count to 4
.forEach(System.out::println); // prints qualified random items without repetition
您可以在java中使用Random()对象。
下面是从ArrayList获取3个随机元素的示例,希望这对您有所帮助。
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class GFG {
// Drive Function
public static void main(String[] args)
{
// create a list of Integer type
List<Integer> list = new ArrayList<>();
// add 5 element in ArrayList
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
GFG obj = new GFG();
// boundIndex for select in sub list
int numberOfElements = 3;
// take a random element from list and print them
System.out.println(obj.getRandomElement(list,
numberOfElements));
}
// Function select an element base on index and return
// an element
public List<Integer> getRandomElement(List<Integer> list,
int totalItems)
{
Random rand = new Random();
// create a temporary list for storing
// selected element
List<Integer> newList = new ArrayList<>();
for (int i = 0; i < totalItems; i++) {
// take a raundom index between 0 to size
// of given List
int randomIndex = rand.nextInt(list.size());
// add element in temporary list
newList.add(list.get(randomIndex));
// Remove selected element from orginal list
list.remove(randomIndex);
}
return newList;
}
}
输出:
[50, 40, 30]
创建一个随机整数数组,并将它们用作数组的索引
int[] indexes = new Random().ints(4, 0, fruitsArray.length).toArray();
for (int i = 0; i < indexes.length; i++) {
System.out.println(fruitsArray[i]);
}