[英]Java how to use TreeMap
I have an TreeMap with for key an Integer and for value Coords (int x, int y). 我有一个TreeMap,其中的键为Integer,值为Coords(int x,int y)。
I would like to get all the values (my coords) associated with an specific key. 我想获取与特定键关联的所有值(我的坐标)。
For exemple : 举个例子 :
key = 1, coords = [0, 0]
key = 1, coords = [0, 1]
key = 2, coords = [1, 0]
key = 3, coords = [1, 1]
foreach myMap.getKeys() as key
do
myMap.getValuesFrom(key)
store it in a new list
end do
I don't really know how to use Map, your helps is welcome. 我真的不知道如何使用地图,欢迎您的帮助。
First point - Map
cannot have two different values associated with the same key. 第一点- Map
不能有两个与同一个键关联的不同值。 If you really need to do this, you can create a map of lists, like this: 如果确实需要执行此操作,则可以创建一个列表列表,如下所示:
Map<Integer, List<Integer>> map = new TreeMap<Integer, List<Integer>>();
The following code traverses the keys of the map and puts related values to the list: 以下代码遍历地图的键并将相关值放入列表:
Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
List<Integer> list = new ArrayList<Integer>();
for (Integer key : map.keySet()) {
list.add(map.get(key));
}
More correct way to do the same thing: 做同一件事的更正确方法:
Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
List<Integer> list = new ArrayList<Integer>(map.values());
If you really need several values mapped to the same key, try this: 如果确实需要将多个值映射到同一键,请尝试以下操作:
Map<Integer, List<Integer>> map = new TreeMap<Integer, List<Integer>>();
for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) {
System.out.println("Map values for key \"" + entry.getKey() + "\":");
for (Integer value : entry.getValue() == null ? new ArrayList<Integer>() : entry.getValue()) {
System.out.print(value + " ");
}
System.out.println();
}
This code simply writes all map keys and its values into System.out
. 此代码仅将所有映射键及其值写入System.out
。
For further information, try to read Map Javadoc and List Javadoc . 有关更多信息,请尝试阅读Map Javadoc和List Javadoc 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.