在Java中排序地图不起作用

Dil*_*lip 2 java sorting map

我正在尝试使用Comparator接口对TreeMap进行排序(将Double作为值和Integer值作为键),但它不起作用.

// Create a tree map
        TreeMap tm = new TreeMap();
        // Put elements to the map
        tm.put(1, new Double(3434.34));
        tm.put(0, new Double(123.22));
        tm.put(4, new Double(1378.00));
        tm.put(2, new Double(99.22));
        tm.put(3, new Double(-19.08));
        List<Map.Entry> valueList = new ArrayList(tm.entrySet());

        // Collections.sort(valueList, new Sort());

        Collections.sort(valueList, new Sort());

        HashMap sortedMap = new HashMap();

        // Get an iterator
        Iterator<Map.Entry> i = valueList.iterator();

        // Display elements
        while (i.hasNext()) {
            Map.Entry object = i.next();
            sortedMap.put(object.getKey(), object.getValue());
        }
        List sortedList = new ArrayList(sortedMap.entrySet());
        Iterator<Map.Entry> iterator = sortedList.iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            System.out.println("Value " + entry.getValue() + "\n");
        }
Run Code Online (Sandbox Code Playgroud)

以下是我的Comparator类

public class Sort implements Comparator<Map.Entry> {

    @Override
    public int compare(Map.Entry o1, Map.Entry o2) {
        // TODO Auto-generated method stub
        double valueOne = (Double) o1.getValue();
        double valueTwo = (Double) o2.getValue();

        int returnValue =
            valueOne > valueTwo ? -1 : (valueOne == valueTwo ? 0 : 1);

        return (valueOne > valueTwo ? -1 : (valueOne == valueTwo ? 0 : 1));
    }

}
Run Code Online (Sandbox Code Playgroud)

但我得到以下输出

Value 123.22

Value 3434.34

Value 99.22

Value -19.08

Value 1378.0

Edited Part

public int compare(Map.Entry o1, Map.Entry o2) {
        // TODO Auto-generated method stub
        double valueOne = ((Double) o1.getValue()).doubleValue();
        double valueTwo = ((Double) o2.getValue()).doubleValue();

        int returnValue =
            valueOne > valueTwo ? -1 : (valueOne == valueTwo ? 0 : 1);

        return (valueOne > valueTwo ? -1 : (valueOne == valueTwo ? 0 : 1));
    }
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 5

HashMap 本质上是无序的.

相反,您可以TreeMap首先使用比较器创建一个.