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