使用 Collections.shuffle()
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
list.add("f");
list.add("g");
System.out.println("随機前:" + JSON.toJSONString(list));
Collections.shuffle(list);
System.out.println("第一次随機後:" + JSON.toJSONString(list));
Collections.shuffle(list);
System.out.println("第二次随機後:" + JSON.toJSONString(list));
}
結果展示:
随機前:["a","b","c","d","e","f","g"]
第一次随機後:["c","d","g","f","e","b","a"]
第二次随機後:["a","b","g","d","e","c","f"]