简体   繁体   中英

Java how to use TreeMap

I have an TreeMap with for key an Integer and for value 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. 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 .

For further information, try to read Map Javadoc and List Javadoc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM