1. 程式人生 > >java list隨機取值

java list隨機取值

public static void main(String[] args) {
List<String> list = new ArrayList<String>();

List<String> randomList = new ArrayList<String>();

建立有順序的list

for (int i = 0; i < 10; i++) {
list.add(i, String.valueOf(i));
               }
for (String i : list) {
System.out.println("輸出的數字為"+i);

                          }

//迴圈三次輸出打亂的list

for (int k = 0; k <3; k++) {
//removeListElement(list,5);
randomList = randomListElement(list,5);
System.out.println("打亂之後的順序為----------");
for (String i : randomList) {
System.out.println("打亂之後輸出的數字為"+i);
                              }
                     }
            }

private static List<String> randomListElement(List<String> list, int i) {
List<String> randomList = new ArrayList<String>();
//隨機打亂list
Collections.shuffle(list);
for (int j = 0; j <i; j++) {
randomList.add(list.get(j));
       }
return randomList;
  }