如果这看起来很简单,请原谅我,但我不能轻易地弄明白。我想过使用循环,但想知道是否有人知道更简单的方法:我有:
Map<String, Integer> map = new HashMap<>();
map.put("ClubB", 1);
map.put("ClubA", 2);
map.put("ClubC", 2);
map.put("ClubD", 2);
map.put("ClubE", 3);
map.put("ClubF", 2);
map.put("ClubG", 2);例如,我需要获取索引3处的键和值,等等。原因是我使用比较器对Map进行排序,并希望显示特定索引处的值已更改。
谢谢你的点子。
更新:
我使用:
HashMap leagueTable = new HashMap();
Map<String, Integer> map = sortByValues(leagueTable);
public <K extends Comparable<K>, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
Comparator<K> valueComparator = new Comparator<K>() {
public int compare(K k1, K k2) {
int compare = map.get(k2).compareTo(map.get(k1));
if (compare == 0) {
return k1.compareTo(k2); // <- To sort alphabetically
} else {
return compare;
}
}
};
Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println( entry.getKey() + ", " + entry.getValue() );
} 发布于 2016-01-18 00:55:56
最后使用了for循环,并与我已经添加到Map中的内容进行了比较:
HashMap<String, Integer> map = new HashMap<>();
map.put("ClubD", 3);
map.put("ClubB", 1);
map.put("ClubA", 2);
map.put("ClubC", 2);
map.put("ClubE", 2);
map.put("ClubF", 2);
map.put("ClubG", 2);
Map<String, Integer> mapResult = instance.sortByValues(map);
String expectedResultKey = "ClubB";
int expectedResultValue = 1;
String resultKey = "";
int resultValue = 0;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
resultKey = entry.getKey();
resultValue = entry.getValue();
}
assertSame(expectedResultKey, resultKey);发布于 2016-01-18 01:45:07
HashMap的没有索引。它们只是将数据存储在键-值对中。
为什么不使用二维数组而不是map作为Map呢?(并给它起一个更合适的名字)
String[][] array = new String[3][3];
array[3] = new String[] { "ClubD" };
array[1] = new String[] { "ClubB" };
array[2] = new String[] { "ClubA", "ClubC", "ClubE", "ClubF", "ClubG" };
System.out.println(array[3][0]);然后,如果你想通过循环这个数组,你只需要这样做:
for (int a = 0; a < array.length; a++)
for (int b = 0; b < array[a].length; b++)
if (array[a][b] != null)
System.out.println("array["+a+"]["+b+"] is: "+array[a][b]);https://stackoverflow.com/questions/34840416
复制相似问题