复杂List排序

package utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 根根据指定的关键字排序List类型的List
 *
 * @author guozi
 */
public class MapListComparator implements Comparator {

 private String key;
 private String orderType;

 /**
  * @param key
  *            排序的关键字
  * @param orderType
  *            排序的方式:"asc" 升序; "desc" 降序
  */
 public MapListComparator(String key) {
  this.key = key;
  this.orderType = "asc";
 }

 public MapListComparator(String key, String orderType) {
  this.key = key;
  this.orderType = orderType;
 }

 public int compare(Object o1, Object o2) {
  Map m1 = (Map) o1;
  Map m2 = (Map) o2;
  if ("desc".equals(orderType)) {
   return (m2.get(key).toString()).compareTo(m1.get(key).toString());
  }
  return (m1.get(key).toString()).compareTo(m2.get(key).toString());
 }

 

 public static void main(String[] args) {
  List l = new ArrayList();
  Map m1 = new HashMap();
  m1.put("id", "1");
  m1.put("name", "aa");
  m1.put("score", 10);
  Map m2 = new HashMap();
  m2.put("id", "2");
  m2.put("name", "bb");
  m2.put("score", 20);
  Map m3 = new HashMap();
  m3.put("id", "3");
  m3.put("name", "cc");
  m3.put("score", 30);
  l.add(m1);
  l.add(m3);
  l.add(m2);

  for (Map m : l) {
   System.out.println(m.get("id") + " = " + m.get("name"));
  }

  System.out.println("==============================");

  Collections.sort(l, new MapListComparator("score", "desc"));
  for (Map m : l) {
   System.out.println(m.get("id") + " = " + m.get("name"));
  }

 }
}

你可能感兴趣的:(java编程积累)