package com.example.demo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class TestApp { /** Comparable是一个内部比较接口,通常对象需要内部排序时直接实现 Comparator是一个外部比较接口,通常在对象中没有实现排序接口而有需要进行排序时实现 **/ public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(2); list.add(4); list.add(3); list.add(1); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } //1 list.sort(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }); //2 list.sort(Integer::compareTo); //3 Collections.sort(list, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } //倒序 list.sort(Comparator.comparing(Integer::intValue).reversed()); list.sort(Comparator.naturalOrder()); //对象按某个字段排序 //倒序 Collections.sort(list,Comparator.comparing(Stu::getAge).reversed()); //正序 list.sort(Comparator.comparing(Stu::getAge)); } }
标签:sort,Java,Comparator,int,list,集合,Integer,排序 From: https://www.cnblogs.com/coderdxj/p/18098615