如何对具有键值对的列表映射进行排序?

发布于 2024-10-21 00:55:12 字数 43 浏览 2 评论 0原文

我在地图中获取特定键的结果列表。怎么排序呢?

提前致谢。

I am getting a list of results in a map for a particular key. How to sort it?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦太阳 2024-10-28 00:55:12

如果您想对键进行排序,请使用 TreeMap


来自您的声明:

我正在获取特定键的地图结果列表。如何排序?

看来你的地图是

Map<String,List<SomeEntity>> map;

你可以从 key 获取对象的 List 然后使用

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 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
    }
}
梦开始←不甜 2024-10-28 00:55:12

如果您询问如何对列表进行排序,请参阅 集合.排序(列表)

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

镜花水月 2024-10-28 00:55:12
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));
        }
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));
        }
寄居人 2024-10-28 00:55:12

进行目视检查的最简单方法是使用地图初始化 TreeMap,然后打印它。

System.out.println("map: " + new TreeMap(myMap));

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));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文