如何根据List<Object>中的Object的某一属性对List进行排序?
首先是Object类
public class StuVO { private String name; private int score; public StuVO(String name, int srore) { this.name = name; this.score = srore; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int srore) { this.score = srore; } }
然后是处理的代码
import com.catk.entity.StuVO; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class ListSort { public static void main(String[] args) { List<StuVO> list = new ArrayList<>(); list.add(new StuVO("AAA",90)); list.add(new StuVO("BBB",150)); list.add(new StuVO("CCC",12)); list.add(new StuVO("DDD",64)); list.add(new StuVO("EEE",5)); for(int i = 0;i < list.size();i++){ System.out.println(list.get(i).getName()+" "+list.get(i).getScore()); } System.out.println("--------"); Collections.sort(list, new Comparator<StuVO>() { @Override public int compare(StuVO o1, StuVO o2) { int i = o1.getScore() - o2.getScore(); return i; } }); for(int i = 0;i < list.size();i++){ System.out.println(list.get(i).getName()+" "+list.get(i).getScore()); } } }
通过Collection.sort进行排序。