public class Demo {
public static void main(String[] args) {
// 创建集合
List<Integer> list = new ArrayList<Integer>();
// 添加元素
for (int i = 1; i <= 5; i++) {
list.add(i);
}
System.out.println(list);// 结果:[1, 2, 3, 4, 5]
// ----------------排序操作----------------
// 1、reverse(List list) - 反转指定列表中的元素的顺序
Collections.reverse(list);
System.out.println(list);// 结果:[5, 4, 3, 2, 1]
// 2、shuffle(List list) - 使用默认随机源对指定列表进行置换
Collections.shuffle(list);
System.out.println(list);// 结果:[2, 3, 4, 1, 5]
// 3、sort(List list) - 根据元素的自然顺序 对指定列表按升序进行排序
Collections.sort(list);
System.out.println(list);// 结果:[1, 2, 3, 4, 5]
// 4、sort(List list, Comparator c) - 根据指定比较器产生的顺序对指定列表进行排序
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
/*
* o1:表示前面的元素,o2:表示后面的元素
* o1 - o2:前面的元素与后面的元素作比较
* o1 - o2:返回正数,表示o1大于o2,交换位置(o1往后移,o2往前移)
* o1 - o2:返回0,表示o1等于o2,位置不变
* o1 - o2:返回负数,表示o1小于o2,交换位置(o1往前移,o2往后移)
* 附:可以理解为升序(顺序)排序(个人理解)
*/
/*
* o1:表示前面的元素,o2:表示后面的元素
* o2 - o1:后面的元素与前面的元素作比较
* o2 - o1:返回正数,表示o2大于o1,交换位置(o1往后移,o2往前移)
* o2 - o1:返回0,表示o2等于o1,位置不变
* o2 - o1:返回负数,表示o2小于o1,交换位置(o1往前移,o2往后移)
* 附:可以理解为降序(倒序)排序(个人理解)
*/
}
});
System.out.println(list);// 结果:[5, 4, 3, 2, 1]
// 5、swap(List list, int i, int j) - 在指定列表的指定位置处交换元素
Collections.swap(list, 0, 1);
System.out.println(list);// 结果:[4, 5, 3, 2, 1]
//6、rotate(List list, int distance) - 根据指定的距离轮换指定列表中的元素
Collections.rotate(list, 3);
System.out.println(list);// 结果:[4, 5, 3, 2, 1]
}
}
java Collections 排序方法
最新推荐文章于 2024-02-15 09:00:00 发布