2

I have a problem with HashMap. I want to put into map:

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

After that I want to sort this map in descending order like this:

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

and after that I want to sort map in ascending order, but only values:

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

This is possible in hashmaps? How I can do this?

edi233
  • 3,511
  • 13
  • 56
  • 97
  • Do you really want to change mapping from key to value in the third step? – Michael Barker Dec 11 '11 at 14:36
  • I need change this values, because in next step I myst do some operations. I next step I must multiply 321 * 0.1, 323 * 0.5 etc. Unless I can do this without change mapping? – edi233 Dec 11 '11 at 14:39

3 Answers3

3

No. HashMap is an implementation of Map insteface that does not preserve any order of keys. It puts keys according to their hash code.

But you have easier solution. You should use TreeMap instead. This class accepts comparator. Use it with your own comparator and you even do not have to sort anything. The keys will be returned according to the comparator. To inverse order you can either use other TreeMap or just say new ArrayList(t.keySet()) and then inverse the order of the list.

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

no, you can't sort by value using HashMap or any of the standard jdk map implementations.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
0

A HashMap does not maintain an order, so it can't be sorted. You should put key and value in an object.

class Pair {
    int key;
    doulbe value;
}

put them in an ArrayList and use Collections.sort() to sort them.

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);
    }

}
stacker
  • 68,052
  • 28
  • 140
  • 210