package com.demo;
public class Student {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return "Student [id=" + this.getId() + "]";
}
}
1.给单个属性排序
package com.demo;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
List<Student> stuList = new ArrayList<Student>();
Student s1 = new Student();
s1.setId("3345");
Student s2 = new Student();
s2.setId("12454");
Student s3 = new Student();
s3.setId("23");
stuList.add(s1);
stuList.add(s2);
stuList.add(s3);
//1.sort
stuList.sort((a,b)->a.getId().compareTo(b.getId()));
stuList.forEach(s -> System.out.println(s.toString()));
//2.sorted
// List<Student> newList1 = stuList.stream().sorted(Comparator.comparing(Student::getId))
// .collect(Collectors.toList());
// newList1.forEach(s -> System.out.println(s.toString()));
//3.sorted 倒序
// List<Student> newList2 = stuList.stream().sorted(Comparator.comparing(Student::getId).reversed())
// .collect(Collectors.toList());
// newList2.forEach(s -> System.out.println(s.toString()));
//3.给list基本数据排序
// List<String> strList = Arrays.asList("234","123","87","43");
// Collections.sort(strList);
// strList.forEach(e -> System.out.println(e));
}
}
2.给多个属性排序
package com.demo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
List<Student> stuList = new ArrayList<Student>();
Student s1 = new Student("222", "zhangsan");
Student s2 = new Student("111", "wanger");
Student s3 = new Student("222", "lishi");
stuList.add(s1);
stuList.add(s2);
stuList.add(s3);
//1.直接使用sort(多属性比较)
stuList.sort(Comparator.comparing(Student::getId).thenComparing(Student::getName));
stuList.forEach(System.out::println);
//2.构建比较器(多属性比较)
Comparator<Student> c = (p, o) -> p.getId().compareTo(o.getId());
c = c.thenComparing((p, o) -> p.getName().compareTo(o.getName()));
stuList.sort(c);
stuList.forEach(s -> System.out.println(s.toString()));
//1.sort(单属性比较)
stuList.sort((a,b)->a.getId().compareTo(b.getId()));
stuList.forEach(s -> System.out.println(s.toString()));
//2.sorted(单属性比较)
List<Student> newList1 = stuList.stream().sorted(Comparator.comparing(Student::getId))
.collect(Collectors.toList());
newList1.forEach(s -> System.out.println(s.toString()));
//3.sorted 倒序
List<Student> newList2 = stuList.stream().sorted(Comparator.comparing(Student::getId).reversed())
.collect(Collectors.toList());
newList2.forEach(s -> System.out.println(s.toString()));
//4.给list基本数据排序
List<String> strList = Arrays.asList("234","123","87","43");
Collections.sort(strList);
strList.forEach(e -> System.out.println(e));
}
}
ps:如果想倒序,只要将p和o反过来即可