JAVASE的TreeMap比较器的实现

flowbean类:

 

 

package mapreduce_flowcount;

import java.util.Map.Entry;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeMap;
/**
 * treemap按照key进行排序。
 * @author THY
 *
 */
public class TreeMapTest {

	public static void main(String[] args) {
		TreeMap<FlowBean,String> tmap = new TreeMap<>(new Comparator<FlowBean>() {
			//重写比较方法,按照FlowBean类中封装的amount,从大到小排序
			@Override
			public int compare(FlowBean o1, FlowBean o2) {
                        //如果amount值一样按照电话进行排序
				if (o2.getAmount()-o1.getAmount()==0) {
					return o1.getPhone().compareTo(o2.getPhone());
				}
				
				return o2.getAmount()-o1.getAmount();
			}
			
		});
		
//		tmap.put("e", 1);
//		tmap.put("a", 13);
//		tmap.put("b", 6);
//		tmap.put("aa", 23);
//		
//		Set<Entry<String, Integer>> entrySet = tmap.entrySet();
//		for (Entry<String, Integer> entry : entrySet) {
//			System.out.println(entry.getKey()+","+entry.getValue());
//		}
			
		FlowBean f1= new FlowBean(5,3,"1299");
		FlowBean f2= new FlowBean(4,2,"1266");
		FlowBean f3= new FlowBean(6,4,"1255");
		FlowBean f4= new FlowBean(3,5,"1244");
		
		tmap.put(f1, null);
		tmap.put(f2, null);
		tmap.put(f3, null);
		tmap.put(f4, null);
		
		Set<Entry<FlowBean, String>> entrySet = tmap.entrySet();
		for (Entry<FlowBean, String> entry : entrySet) {
			System.out.println(entry.getKey()+","+entry.getValue());
		}
	}
}

 

没有更多推荐了,返回首页