List Collections sort
package gather; import java.util.ArrayList; import java.util.Collections; public class CollecSortTest { public static void main(String[] args) { // System.out.println(list.isEmpty()); 判断结合是否为空 ArrayList<String> list1 = new ArrayList<>(); Collections.sort(list1); //方法1 list1.add("222"); list1.add("1"); list1.add("444"); list1.add("33"); // list1.sort(new ComparatorOne()); //方法2 Collections.sort(list1, ( first, second) -> first.length() - second.length());// 方法5 lambda表达式 ArrayList<Student> list2 = new ArrayList<>(); Student student1 = new Student(); student1.setAge(1); Student student2 = new Student(); student2.setAge(2); Student student3 = new Student(); student3.setAge(3); list2.add(student3); list2.add(student2); list2.add(student1); // list2.sort(new ComparatorTwo()); //方法3 Collections.sort(list2, ( first, second) -> second.getAge() - first.getAge());// 方法5 lambda表达式 System.out.println("true"); } }
package gather; import java.util.Comparator; public class ComparatorOne implements Comparator<String> { @Override public int compare(String arg0, String arg1) { System.out.println("---ComparatorOne---"); return arg0.length() - arg1.length(); } }
package gather; import java.util.Comparator; public class ComparatorTwo implements Comparator<Student>{ @Override public int compare(Student o1, Student o2) { System.out.println("---ComparatorTwo---"); return o1.getAge()-o2.getAge(); } }