Collections.shuffle(数组/集合);
List<String> list=new ArrayList<>();
list.add("1");
list.add("a");
list.add("b");
list.add("c");
list.add("d");
/*随机打乱集合顺序*/
Collections.shuffle(list);
System.out.println(list); //[b, d, c, 1, a]
Collections.sort()
按默认排序 /*排序*/ Collections.sort(list); System.out.println(list); //[1, a, b, c, d]按自定义规则排序 Comparator(o1,o2) o1-o2 为升序 o2-o1 为降序
public class Students {
private String name;
private String ages;
。。。//省略get set
}
//main()
/*按一定规则排序*/
List<Students> sl=new ArrayList<>();
sl.add(new Students("zhangsan","20"));
sl.add(new Students("lisi","30"));
sl.add(new Students("wangwu","40"));
sl.add(new Students("zhaoliu","15"));
Collections.sort(sl, new Comparator<Students>() {
@Override
public int compare(Students o1, Students o2) {
int a=Integer.parseInt(o1.getAges());
int b=Integer.parseInt(o2.getAges());
return a-b;
}
});
System.out.println(sl);//[Students{name='zhaoliu', ages='15'}, Students{name='zhangsan', ages='20'}, Students{name='lisi', ages='30'}, Students{name='wangwu', ages='40'}]