package cc;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
/*
* 需求:将map集合中的元素按数字排序,数字相同的按字典顺序排序
*/
public class TreeMapTest2
{
public static void main(String[] args)
{
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
map.put("abc", 5);
map.put("mvpd", 3);
map.put("zz", 3);
map.put("itcast", 1);
map.put("qq", 4);
map.put("vip", 5);
System.out.println(map);
Set<Map.Entry<String, Integer>> set = new TreeSet<Map.Entry<String, Integer>>(new MyComparator());
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
for (Map.Entry<String, Integer> entry : entrySet)
{
set.add(entry);
}
//排序后的结果
System.out.println(set);
//输出每一个
for(Iterator<Map.Entry<String, Integer>> ite = set.iterator(); ite.hasNext();)
{
System.out.println(ite.next());
}
}
}
//定义比较器,将Map中的key,和value看做一个整体
class MyComparator implements Comparator<Map.Entry<String, Integer>>
{
@Override
public int compare(Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2)
{
if(entry1.getValue() == entry2.getValue())
{
return entry1.getKey().compareTo(entry2.getKey());
}
return entry1.getValue() - entry2.getValue();
}
}
|