我有一个多维数组,包含键和值。 根据排序值,我必须安排键值 对于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
答案 0 :(得分:1)
使用TreeMap将值映射到键 (所以你要改变他们对你案件的意义)。
只需在TreeMap中添加元素,您就可以对它们进行排序。
如果您没有多个键映射到相同的值,这将有效 (最后一句中的键/值用于你的意思,而不是通常的Map意思)。
答案 1 :(得分:1)
喜欢这个
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));
<强>输出强>
[[8, 1], [4, 2], [6, 2], [3, 4], [1, 5]]
答案 2 :(得分:1)
试试这个:
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));
}
答案 3 :(得分:0)
你收藏不好。你应该使用map。