排序
對List進行排序,有兩種辦法
第一個是用java提供的工具類Collections提供的sort方法進行排序
廢話不多說,上代碼
首先定義一個Student
public class Student { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Student(int age, String name) { super(); this.age = age; this.name = name; } }
下面是進行排序的代碼
public static void main(String[] args) { List<Student> list= new ArrayList<Student>(); list.add(new Student(5, "aa")); list.add(new Student(7, "bb")); list.add(new Student(6, "cc")); Collections.sort(list,new Comparator<Student>(){ @Override public int compare(Student o1, Student o2) { //會把集合里面的對象兩兩傳進方法里面比較,這里比較age,降序就O2-O1,升序就O1-O2 return o2.getAge()-o1.getAge(); } }); //打印list每一項的age list.forEach(a -> System.out.println(a.getAge())); } }
第二種方法:
List集合提供了sort方法,依然用Student做集合,進行排序
public static void main(String[] args) { List<Student> list= new ArrayList<Student>(); list.add(new Student(5, "aa")); list.add(new Student(7, "bb")); list.add(new Student(6, "cc")); //差別在這里,這里直接用list的sort方法,不需要吧list作為參數,其他的和Comparable排序是一樣的 list.sort(new Comparator<Student>(){ @Override public int compare(Studento1, Studento2) { //會把集合里面的對象兩兩傳進方法里面比較,這里比較age,降序就O2-O1,升序就O1-O2 return o2.getAge()-o1.getAge(); } }); //打印list每一項的age list.forEach(a -> System.out.println(a.getAge())); } }
對list進行分組:
同樣的,用Student的集合作為示例,代碼如下
public class test2 { /** * 創建比較器 */ public static <T> List<List<T>> dividerList(List<T> list,Comparator<? super T> comparator) { List<List<T>> lists = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { boolean isContain = false; for (int j = 0; j < lists.size(); j++) { if (lists.get(j).size() == 0||comparator.compare(lists.get(j).get(0),list.get(i)) == 0) { lists.get(j).add(list.get(i)); isContain = true; break; } } if (!isContain) { List<T> newList = new ArrayList<>(); newList.add(list.get(i)); lists.add(newList); } } return lists; } public static void main(String[] args) { List<Student> list = new ArrayList<Student>(); //實在不會起名字,用字母代替吧 list.add(new Student(17,"aa")); list.add(new Student(15,"bb")); list.add(new Student(16,"cc")); list.add(new Student(15,"dd")); list.add(new Student(16,"ee")); list.add(new Student(17,"ff")); List<List<Student>> list2 = dividerList(list, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { // 按年齡分組,這里注意一點,返回的值為0,就會認為這兩個Studeng是一組的,返回其他值,則認為不是,所以下面的-1可以替換為任意非0數字 return o1.getAge == o2.getAge ? 0:-1; //也可以按照姓名分組,返回結果如下,因為是比較兩個值是否相等,所以先后是沒有區別的 //return o1.getName().compareTo(o1.getName()) } });
for(List<Student> stList: list2){
stList.forEach(a -> System.out.printIn(a.getName+":"+a.getAge));
System.out.printIn("=========================================");
}
} }