1.
public class DemoTreeMap3 { public static void main(String[] args) { System.out.println("------对hashMap按照key进行排序----------"); Mapmap = new HashMap (); map.put(new Car("凯迪拉克",50),"看iadilake1"); map.put(new Car("法拉利",100),"阿迪发送发的"); map.put(new Car("大众", 20), "迈腾"); Comparator c = new CarComparator(); Map map2 = new TreeMap (c); map2.putAll(map); Set set = map2.keySet(); for (Car car : set) { System.out.println(car.getPrice()+"--"+car.getType()); } System.out.println("------对hashMap按照value进行排序----------"); //对HashMap按照value进行排序 Map map3 = new HashMap (); map3.put("大众",new Car("凯迪拉克",50)); map3.put("法拉利",new Car("法拉利",100)); map3.put("福特",new Car("福特", 20)); //第一步:把待排序map集合的引用传递进入自定义比较器 //第二步:在自定义比较器中,加入成员变量,接收map集合的引用 Comparator compar = new CarComparator2(map3); Map treeMap = new TreeMap (compar); treeMap.putAll(map3); Collection cars = treeMap.values(); for (Car car : cars) { System.out.println(car.getPrice()+"--"+car.getType()); } }}
import java.util.Comparator;public class CarComparator implements Comparator{ @Override public int compare(Car o1, Car o2) { return (int)(o1.getPrice()-o2.getPrice()); }}
public class CarComparator2 implements Comparator{ private Map map; public CarComparator2(Map map3) { this.map = map3; } @Override public int compare(String key1, String key2) { Car car1 = map.get(key1); Car car2 = map.get(key2); return (int) (car1.getPrice() - car2.getPrice()); }}