I have a Map that has strings for both keys and values.
Data is like following:
\"question1\", \"1\"
\"question9\", \"1\"
\"que
To sort a Map<K, V>
by key, putting keys into a List<K>
:
List<K> result = map.keySet().stream().sorted().collect(Collectors.toList());
To sort a Map<K, V>
by key, putting entries into a List<Map.Entry<K, V>>
:
List<Map.Entry<K, V>> result =
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toList());
Last but not least: to sort strings in a locale-sensitive manner - use a Collator (comparator) class:
Collator collator = Collator.getInstance(Locale.US);
collator.setStrength(Collator.PRIMARY); // case insensitive collator
List<Map.Entry<String, String>> result =
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey(collator))
.collect(Collectors.toList());
Use a TreeMap!
We can also sort the key by using Arrays.sort method.
Map<String, String> map = new HashMap<String, String>();
Object[] objArr = new Object[map.size()];
for (int i = 0; i < map.size(); i++) {
objArr[i] = map.get(i);
}
Arrays.sort(objArr);
for (Object str : objArr) {
System.out.println(str);
}
A good solution is provided here. We have a HashMap
that stores values in unspecified order. We define an auxiliary TreeMap
and we copy all data from HashMap into TreeMap using the putAll
method. The resulting entries in the TreeMap are in the key-order.
This code can sort a key-value map in both orders i.e. ascending and descending.
<K, V extends Comparable<V>> Map<K, V> sortByValues
(final Map<K, V> map, int ascending)
{
Comparator<K> valueComparator = new Comparator<K>() {
private int ascending;
public int compare(K k1, K k2) {
int compare = map.get(k2).compareTo(map.get(k1));
if (compare == 0) return 1;
else return ascending*compare;
}
public Comparator<K> setParam(int ascending)
{
this.ascending = ascending;
return this;
}
}.setParam(ascending);
Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}
As an example:
Map<Integer,Double> recommWarrVals = new HashMap<Integer,Double>();
recommWarrVals = sortByValues(recommWarrVals, 1); // Ascending order
recommWarrVals = sortByValues(recommWarrVals,-1); // Descending order
Assuming TreeMap is not good for you (and assuming you can't use generics):
List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.