-2

I have an multidimensional array consists of key and value. Based on sort value i have to arrange key values For Eg:

Multidimensional array:
key Value
1    5
4    2
3    4
8    1
6    2

I have to arrange keys based ascending order of values 
Answer:
8 1
4 2
6 2
3 4
1 5 
Jeevan Roy dsouza
  • 653
  • 3
  • 12
  • 32

4 Answers4

1

Use a TreeMap in which you put values mapped to keys (so you reverse their meanings for your case).

Just add the elements in the TreeMap and you will have them sorted.

This will work if you don't have multiple keys mapped to the same value (key/value in this last sentence is used in your meaning, not in the usual Map meaning).

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
1

do like this

Integer[][] array ={{1,5},{4,2},{3,4},{8,1},{6,2}};
Arrays.sort(array, new Comparator<Integer[]>() {
    @Override
    public int compare(Integer[] o1, Integer[] o2) {
    return o1[1].compareTo(o2[1]);
    }
});
System.out.println(Arrays.deepToString(array));

Output

[[8, 1], [4, 2], [6, 2], [3, 4], [1, 5]]
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
1

Try this one:

static class ValueComparator implements Comparator<String> {

    Map<String, Integer> base;

    ValueComparator(Map<String, Integer> base) {
        this.base = base;
    }

    @Override
    public int compare(String a, String b) {
        Integer x = base.get(a);
        Integer y = base.get(b);
        if (x.equals(y)) {
            return a.compareTo(b);
        }
        return x.compareTo(y);
    }
}


HashMap<String, Integer> map = new HashMap<String, Integer>();
ValueComparator vc = new ValueComparator(map);
TreeMap<String, Integer> sorted = new TreeMap<String, Integer>(vc);

map.put("z",30);
map.put("e",10);
map.put("b",20);
map.put("c",20);

sorted.putAll(map);

for (String key : sorted.keySet()) {
    System.out.println(key + " : " + sorted.get(key)); 
}
Ivaylo Slavov
  • 8,839
  • 12
  • 65
  • 108
0

You have bad collection. You should have used map.

Marcin Szymczak
  • 11,199
  • 5
  • 55
  • 63