Niranjan Kumar
Niranjan Kumar

Reputation: 869

How to sort a map of list having key-value pairs?

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

Answers (4)

Koekiebox
Koekiebox

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

Jigar Joshi
Jigar Joshi

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

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

lindsten
lindsten

Reputation: 88

If you're asking how to sort a list, see Collections.sort(List).

Upvotes: 1

Related Questions