java对list进行排序
使用Colletions.sort方法
import java.util.*;
public class Main {
public static void main(String[] args) {
List listStu = new ArrayList<>();
listStu.add(new Student(98));
listStu.add(new Student(50));
listStu.add(new Student(70));
listStu.add(new Student(46));
listStu.add(new Student(98));
listStu.add(new Student(100));
listStu.add(new Student(68));
System.out.println(listStu);
Collections.sort(listStu,new Student());
System.out.println(listStu);
}
}
class Student implements Comparator{
int grade;//成绩
public Student(int grade){
this.grade = grade;
}
public Student(){}
public String toString(){
return String.valueOf(grade);
}
@Override
public int compare(Student o1, Student o2) {
if(o1.grade<o2.grade)
return -1;
else if(o1.grade>o2.grade)
return 1;
else
return 0;
}
}
java对map进行排序
先将map转化成Map.Entry的列表,再对该列表进行排序,与上面的对list排序一致。
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String,Student> map = new HashMap<>();
map.put(“小明”,new Student(90));
map.put(“小花”,new Student(100));
map.put(“小君”,new Student(90));
map.put(“小李”,new Student(83));
map.put(“小兰”,new Student(75));
System.out.println(map);
List<Map.Entry<String,Student>> listStu = new ArrayList<>(map.entrySet());
Collections.sort(listStu, new Comparator<Map.Entry<String, Student>>() {
@Override
public int compare(Map.Entry<String, Student> o1, Map.Entry<String, Student> o2) {
if(o1.getValue().grade<o2.getValue().grade)
return -1;
else if(o1.getValue().grade>o2.getValue().grade)
return 1;
else
return 0;
}
});
System.out.println(listStu);
}
}
class Student{
int grade;//成绩
public Student(int grade){
this.grade = grade;
}
public Student(){}
public String toString(){
return String.valueOf(grade);
}
}
输出如下:
ps,若需要倒排序时,可以传入Collections.reverseOrder()这个比较器,或者在重写compare方法时按照实际的需求重写即可。