码迷,mamicode.com
首页 > 编程语言 > 详细

TreeMap按照value值进行排序

时间:2016-04-06 15:33:32      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:treemap排序

package demo1;


import java.util.Comparator;

import java.util.HashMap;

import java.util.Map;

import java.util.TreeMap;


public class Testing {

public static void main(String[] args) {

HashMap<String, Double> map = new HashMap<>();

ValueComparator vc = new ValueComparator(map);

TreeMap<String, Double> sorted_map = new TreeMap<>(vc);

map.put("A", 432.3);

map.put("B", 44.3);

map.put("C", 46.3);

map.put("D", 43.3);

sorted_map.putAll(map);

System.out.println(map);

System.out.println(sorted_map);

}

}


class ValueComparator implements Comparator<String>{

private Map<String, Double> base;

public ValueComparator(Map<String, Double> base) {

this.base = base;

}


@Override

public int compare(String a, String b) {

if (base.get(a) >= base.get(b)) {

return 1;

}

return -1;

}

}


TreeMap按照value值进行排序

标签:treemap排序

原文地址:http://11371955.blog.51cto.com/11361955/1760839

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!