HashMaps和操作

时间:2011-12-11 14:33:34

标签: java sorting hashmap

我遇到了HashMap的问题。 我想把它放到地图上:

key - 320, value - 0.1
key - 321, value - 0.7
key - 322, value - 0.5
key - 323, value - 0.6

之后我想按照这样的降序对这个地图进行排序:

key - 321, value - 0.7
key - 323, value - 0.6
key - 322, value - 0.5
key - 320, value - 0.1

之后我想按升序排序地图,但只有值:

key - 321, value - 0.1
key - 323, value - 0.5
key - 322, value - 0.6
key - 320, value - 0.7

这在哈希映射中是可能的吗?我怎么能这样做?

3 个答案:

答案 0 :(得分:3)

没有。 HashMap是Map insteface的一个实现,它不保留任何键的顺序。它根据哈希码放置密钥。

但是你有更简单的解决方案。您应该使用TreeMap。该类接受比较器。与您自己的比较器一起使用它甚至不必排序任何东西。将根据比较器返回键。要反向排序,您可以使用其他TreeMap,也可以只说new ArrayList(t.keySet())然后反转列表的顺序。

答案 1 :(得分:0)

不,您不能使用HashMap或任何标准的jdk地图实现按值排序。

答案 2 :(得分:0)

HashMap不维护订单,因此无法对其进行排序。你应该把键和值放在一个对象中。

class Pair {
    int key;
    doulbe value;
}

将它们放在ArrayList中并使用Collections.sort()对它们进行排序。

class Pair {
    int key;
    double value;

    public Pair(int key, double value) {
        this.key = key;
        this.value = value;
    }
}

class Desc implements Comparator<Pair> {
    @Override
    public int compare(Pair o1, Pair o2) {
        return (int) Math.signum(o1.value - o2.value);
    }
}

class Asc implements Comparator<Pair> {
    @Override
    public int compare(Pair o1, Pair o2) {
        return (int) Math.signum(o2.value - o1.value);
    }
}

public class Test {
    public static void dump(Collection<Pair> col) {
        for ( Pair p :col ) {
            System.out.println("key = " + p.key + " value = " + p.value );
        }
    }
    public static void main(String[] args) {
        ArrayList<Pair> p = new ArrayList<Pair>();
        for (int i = 320; i < 325; i++) {
            p.add(new Pair(i, (double) i / 1000));
        }
        Collections.sort(p, new Asc());
        dump(p);
        System.out.println("------------------------");
        Collections.sort(p, new Desc());
        dump(p);
    }

}