import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class TestListSort { private String name; private int score; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public TestListSort(String name, int score) { super(); this.name = name; this.score = score; } public static void main(String[] args) { List<TestListSort> list = new ArrayList<>(); list.add(new TestListSort("张三",100)); list.add(new TestListSort("李四", 98)); list.add(new TestListSort("王五", 99)); list.add(new TestListSort("赵六", 98)); list.add(new TestListSort("马七", 89)); Collections.sort(list, new Comparator<TestListSort>() { @Override public int compare(TestListSort o1, TestListSort o2) { int i = o1.getScore() - o2.getScore(); return i; } }); for (TestListSort testListSort:list){ System.out.println("姓名:" testListSort.getName() "\t" "分数:" testListSort.getScore()); } } }

list集合去重的常见几种方式(List集合的两种排序方式)(1)

当用o1-o2时,是正序排列,当o2-o1时,是倒序排列。

import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Test implements Comparable<Test> { private String name; private int score; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public Test(String name, int score) { super(); this.name = name; this.score = score; } @Override public int compareTo(Test o) { int i = this.score - o.score; //正序排列// int i = o.score-this.score;//倒序排列 return i; } public static void main(String[] args) { List<Test> list = new ArrayList<>(); list.add(new Test("张三",100)); list.add(new Test("李四", 98)); list.add(new Test("王五", 99)); list.add(new Test("赵六", 98)); list.add(new Test("马七", 89)); Collections.sort(list); for (Test test:list){ System.out.println("姓名:" test.getName() "\t" "分数:" test.getScore()); } } }

list集合去重的常见几种方式(List集合的两种排序方式)(2)

,