如何从数组中随机选择四个元素而无需在Java中重复?

时间:2019-04-13 12:18:25

标签: java arrays random

让我们说:

String[] fruitsArray = new String[] {"apple", "orange", "pear", "banana", "cherry", "blueberry", "papaya", "litchi"};

如何从该数组中随机选择四个元素而不重复?

示例结果为["orange", "pear","blueberry","litchi"]["apple", "orange","orange","papaya"]之类的结果是不可接受的。

3 个答案:

答案 0 :(得分:5)

与使用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

答案 1 :(得分:0)

您可以在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]

答案 2 :(得分:0)

创建一个随机整数数组,并将其用作该数组的索引

int[] indexes = new Random().ints(4, 0, fruitsArray.length).toArray();
for (int i = 0; i < indexes.length; i++) {
    System.out.println(fruitsArray[i]);
}