Java中List的排序和List的MAp
这里是一个类中类去实现条件优先排序的问题
package com.sun; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Demo { public Demo() { // TODO Auto-generated constructor stub } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int a= 0; Dob db = new Dob(); Dob db1 = new Dob(); Dob db2 = new Dob(); db.setName("sun"); db.setAge(20); db.setSex(3); db1.setName("zhi"); db1.setAge(22); db1.setSex(1); db2.setName("yan"); db2.setAge(21); db2.setSex(2); List<Dob> as = new ArrayList<Dob>(); System.out.println("as="+as.size()); as.add(db); as.add(db1); as.add(db2); Collections.sort(as, new Comparator<Dob>() { //比较。如果年龄不同先比较年龄 ,相同就比较性别 public int compare(Dob arg0, Dob arg1) { int flg = arg0.getAge().compareTo(arg1.getAge()); if(flg==0){ return arg0.getSex().compareTo(arg1.getSex()); }else{ return arg0.getAge().compareTo(arg1.getAge()); } } }); for (Dob p : as) { System.out.println(p.getName()); System.out.println(p.getAge()); } System.out.println("as="+as.size()); } } class Dob { public String name; public Integer age; public Integer sex; 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 Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } }
LIst中的MAp
public void listSort(List<Map<String,Object>> resultList) throws Exception{ // resultList是需要排序的list,其内放的是Map // 返回的结果集 Collections.sort(resultList,new Comparator<Map<String,Object>>() { public int compare(Map<String, Object> o1,Map<String, Object> o2) { //o1,o2是list中的Map,可以在其内取得值,按其排序,此例为升序,s1和s2是排序字段值 //String FileNumber = GetFileKeyNumber(fileInfo.getKey(),2,2); Map.Entry<String, Object> fileInfo1 = null; Map.Entry<String, Object> fileInfo2 = null; Integer s1 = 0; Integer s2 = 0; Iterator<Map.Entry<String, Object>> fileMap = o1.entrySet().iterator(); while (fileMap.hasNext()) { fileInfo1 = fileMap.next(); s1 = Integer.parseInt(GetFileKeyNumber(fileInfo1.getValue().toString(),2,2)); } Iterator<Map.Entry<String, Object>> fileMap2 = o2.entrySet().iterator(); while (fileMap2.hasNext()) { fileInfo2 = fileMap2.next(); s2 = Integer.parseInt(GetFileKeyNumber(fileInfo2.getValue().toString(),2,2)); } if(s1>s2) { return 1; }else { return -1; } } }); }