首页 > 代码库 > TreeMap排序
TreeMap排序
import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class MapSort { public TreeMap<String,Double> sort(HashMap<String,Double> map){ ValueComparator bvc = new ValueComparator(map); TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc); sorted_map.putAll(map); return sorted_map; } public static void main(String[] args) { HashMap<String,Double> map = new HashMap<String,Double>(); map.put("A",99.5); map.put("B",67.4); map.put("C",67.4); map.put("D",67.3); TreeMap<String,Double> sorted_map = new MapSort().sort(map); System.out.println("unsorted map: "+map); System.out.println("results: "+sorted_map); } } class ValueComparator implements Comparator<String> { Map<String, Double> base; public ValueComparator(Map<String, Double> base) { this.base = base; } // Note: this comparator imposes orderings that are inconsistent with equals. public int compare(String a, String b) { if (base.get(a) >= base.get(b)) { return -1; } else { return 1; } // returning 0 would merge keys } }
TreeMap排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。