开发者

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

I am getting a list of开发者_如何学Python results in a map for a particular key. How to sort it?

Thanks in advance.


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
    }
}


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


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));
        }


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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜