如何基于“键"更改TreeMap中的条目顺序 [英] How to change the sequence of entries in TreeMap based on the 'Key'

查看:135
本文介绍了如何基于“键"更改TreeMap中的条目顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Map<String,List<UserVO>> studentsByCountry = new TreeMap<String,List<UserVO>>();

显示为:

key=CountryA , value = List<UserVO>
key=CountryB , value = List<UserVO>
key=CountryC , value = List<UserVO>

我可以重新排列此Map以便根据国家/地区的displayOrder显示.显示顺序为countryC = 1,countryB = 2& countryA = 3.我想显示为

Can I reshuffle this Map so that I display according to the displayOrder of the countries. Display order is countryC=1, countryB=2 & countryA=3. I want to display like

key=CountryC , value = List<UserVO>
key=CountryB , value = List<UserVO>
key=CountryA , value = List<UserVO>

一个选择是将sortOrderNumber附加到键上. For example 1_CountryC, 2_CountryB & 3_CountryA

One option is to append the sortOrderNumber to the key. For example 1_CountryC, 2_CountryB & 3_CountryA

我可以通过常规Java做到吗?

Can I do it via conventional Java?

推荐答案

您应使用new TreeMap<String, List<UserVO>>();

Map<String, List<UserVO>> sortedMap = new TreeMap<>(Collections.reverseOrder());
sortedMap.putAll(myMap);

灵感来自于:排序降序:Java Map

如果您想要无序地图,则应使用HashMap

Java中的TreeMap是Map接口的实现之一.它与其他实现HashMap的不同之处在于,它不同于HashMap which is unorderedTreeMap is Sorted.

TreeMap in Java is one of the implementations of the Map interface. How it differs from the other implementation HashMap is that unlike HashMap which is unordered, TreeMap is Sorted.

这篇关于如何基于“键"更改TreeMap中的条目顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆