sortedmap

How to use SortedMap interface in Java?

强颜欢笑 提交于 2019-11-26 15:36:54
问题 I have a Map<Float, MyObject> What is the best way to keep the map sorted according to the float? Is SortedMap the best answer? TreeMap ? How do I use it? I only create the map once and replace the MyObject frequently using myMap.put() and myMap.get() . 回答1: I would use TreeMap , which implements SortedMap . It is designed exactly for that. Example: Map<Integer, String> map = new TreeMap<Integer, String>(); // Add Items to the TreeMap map.put(1, "One"); map.put(2, "Two"); map.put(3, "Three");

Java TreeMap Comparator

拈花ヽ惹草 提交于 2019-11-26 05:33:31
问题 I need a comparator for a TreeMap. Should I write this anonymously in the constructor for my TreeMap? How else could I write my comparator. Currently, Java does not like my code (can I do this anonymously?): SortedMap<String, Double> myMap = new TreeMap<String, Double>(new Comparator<Entry<String, Double>>() { public int compare(Entry<String, Double> o1, Entry<String, Double> o2) { return o1.getValue().compareTo(o2.getValue()); } }); Can I do the above anonymously? How else could I do this? I