How to sort a key of a map
How to sort (any kind of sorting) a key of a map(treemap or hashmap)
i have a problem and it goes like this.
i have a map that has a key of
27527-683,
27525-1179, 27525-1571, 27525-1813, 27525-4911, 27526-1303, 27526-3641, 27525-3989, 27525-4083, 27525-4670, 27526-4102, 27526-558, 27527-2411, 27527-4342this开发者_C百科 is the list of keys and the value for each of the key is a list.
now, how can i sort this key in ascending order by number.ex. if i want to sort : 1,2,11,20,31,3,10
i want to have as output is : 1,2,3,10,11,20,31 but when i use the autosort of treemap the output goes : 1,10,11,2,20,3,31how can i sort it in ascending order by numeric?
please help me. i can't think of anymore ways because this is my first time handling map and listYour keys are Strings. The natural ordering of strings is lexicographical. You either need to specify a custom comparator in the constructor of the TreeMap, or use an Integer key.
Furthermore, you can better represent a Map<Key, List<Value>>
as a Google Guava Multimap
, see for example SortedSetMultimap.
Continuing with the Guava example:
Multimap<Integer, Person> multimap = SortedSetMultimap.create(Ordering.natural(), Ordering.arbitrary());
multimap.put(1, x);
multimap.put(1, y);
multimap.put(2, z);
multimap.put(1, a);
Then
multimap.get(1)
will return a set containing [x, y, a] in some arbitrary order.
multimap.keys()
will return a sorted set of [1, 2].
Your keys are currently Strings, that you would appear to rather handle like Integers. You will need to reformulate how you handle the map object, as many people here have suggested (it may be the correct method). An easier method involves using that list of keys you have copied us in on.
I see there is a way to output the list of keys. Sort that however you like. Arrays and lists are easily sorted by built in commands from your runtime environment. You might have to first split those elements at the hyphen.
I'd recommend a book on Data Structures.
Use SortedMap, for example, java.util.TreeMap
.
keyword : SortedMap
SortedMap<Integer, Integer> s = new TreeMap<Integer, Integer>();
s.put(1, 1);
s.put(4, 2);
s.put(2, 3);
System.out.println(s); //{1=1, 2=3, 4=2}
also look at this example
精彩评论