package com.bugyun.po;
public class Student {
private String name;
private Integer age;
private Float score ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Float getScore() {
return score;
}
public void setScore(Float score) {
this.score = score;
}
public Student(String name, Integer age, Float score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
}
}
ListSort.java
package com.bugyun.demo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.bugyun.po.Student;
import com.google.common.collect.Lists;
/**
*
* list 排序
* 1. 通过 Lambda 排序
* 2. 通过 初始化 方法
*
* @author Administrator
*/
public class ListSort {
public static void main(String[] args) throws Exception {
ListSort listSort = new ListSort();
Student one = new Student("liKui", 22, 65.0f);
Student two = new Student("songJiang", 55, 71.0f);
Student three = new Student("wuSong", 45, 80.0f);
Student four = new Student("sunErNiang", 80, 98f);
Student five = new Student("liGui", 22, 19.0f);
List<Student> humanList = new ArrayList<>();
humanList.add(one);
humanList.add(two);
humanList.add(three);
humanList.add(four);
humanList.add(five);
ArrayList<Student> humanListTwo = Lists.newArrayList(one, two, three, four, five);
listSort.sortByAgeWithLambda(humanList);
listSort.sortByAgeWithInstanceMethod(humanList);
listSort.sortByAgeScoreWithComparator(humanList);
// listSort.sortByAgeWithLambda(humanListTwo);
// listSort.sortByAgeWithInstanceMethod(humanListTwo);
// listSort.sortByAgeScoreWithComparator(humanListTwo);
}
/**
* 通过 Lambda 对学生年龄进行排序
* @param humanList
* @throws Exception
*/
public void sortByAgeWithLambda(List<Student> humanList) throws Exception {
System.out.println("\n----------美丽的分割线----------");
humanList.sort((Student h1, Student h2) -> h1.getAge().compareTo(h2.getAge()));
printList(humanList);
}
/**
* 通过 默认方法 对学生年龄进行排序
* @param humanList
* @throws Exception
*/
public void sortByAgeWithInstanceMethod(List<Student> humanList) throws Exception {
System.out.println("\n----------美丽的分割线----------");
Collections.sort(humanList, Comparator.comparing(Student::getAge));
printList(humanList);
}
public void sortByAgeScoreWithComparator(List<Student> humanList) throws Exception {
System.out.println("\n----------美丽的分割线----------");
Comparator<Student> comparator = (h1, h2) -> {
if (h1.getAge().equals(h2.getAge())) {
return Float.compare(h1.getScore(), h2.getScore());
}
return h1.getAge().compareTo(h2.getAge());
};
humanList.sort(comparator);
printList(humanList);
}
private void printList(List<Student> humanList) {
for (Student human : humanList) {
System.out.println(human);
}
/**
* 对集合洗牌,打乱顺序
*/
Collections.shuffle(humanList);
}
}