Reputation: 869
I am getting a list of results in a map for a particular key. How to sort it?
Thanks in advance.
Upvotes: 2
Views: 4668
Reputation: 5973
Map<String, String> mapie = new Hashtable<String, String>();
mapie.put("D", "the letter D");
mapie.put("C", "the letter C");
mapie.put("A", "the letter A");
mapie.put("B", "the letter B");
Set<String> keys = mapie.keySet();
List<String> keyColList = new ArrayList<String>();
keyColList.addAll(keys);
**You can also make use of a Comparator if you are using a custom object.**
Collections.sort(keyColList);
for(String keyIndex:keyColList){
System.out.println("Key: "+ keyIndex + " has value: "+mapie.get(keyIndex));
}
Upvotes: 1
Reputation: 240996
if you want to sort keys then go for TreeMap
from your statement :
I am getting a list of results in a map for a particular key. How to sort it?
it seems your map is
Map<String,List<SomeEntity>> map;
you can get List
of Objects from key
then use
Collections.sort(list, your_custom_implementation_of_comparator)
public class CustomComparator implements Comparator<SomeEntity> {
@Override
public int compare(SomeEntity o1, SomeEntity o2) {
//logic goes here
}
}
Upvotes: 3
Reputation: 75426
The easiest way to do this for visual inspection is to initialize a TreeMap with your map, and then print it.
System.out.println("map: " + new TreeMap(myMap));
Upvotes: 0