[英]sort arraylist with key ascending
map = new LinkedHashMap<String, String>();
list = new ArrayList<HashMap<String, String>>();
map.put("id", id);
map.put("amt", amt);
list.add(map);
How to sort the list with ascending order of amt
. 如何按照amt
升序对列表进行排序。 I was unable to do this. 我无法做到这一点。 I'd really appreciate any help. 我真的很感激任何帮助。
I am adding id
, amt
in loop. 我正在添加id
, amt
in循环。 How to sort with key as amt
? 如何用密钥排序为amt
?
id=1,2,3,4,5
amt=1000,33333,77,9087,5432
Simply use TreeMap
: 只需使用 TreeMap
:
Map<String, String> map = new TreeMap<String, String>();
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
map.put("id", "id");
map.put("amd", "amd");
list.add(map);
System.out.println(list);
Output: 输出:
[{amd=amd, id=id}]
Now if the Id
is in upper case and amd
in lower case then you should to override the default behavior of TreeMap
using Comparator
in the constructor (to ensure that the sorting for strings keys is correct): 现在,如果Id
是大写并且amd
是小写,那么你应该在构造函数中使用Comparator
覆盖TreeMap
的默认行为(以确保字符串键的排序是正确的):
Map<String, String> map = new TreeMap<String, String>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.toLowerCase().compareTo(o2.toLowerCase());
}
});
Your question is not very clear as at some point you seem to mention sorting a list with only one element (your map). 你的问题不是很清楚,因为在某些时候你似乎提到只用一个元素(你的地图)排序一个列表。 But I assume you want to sort the keys in that map (either inside the map or after adding them all to some list). 但我假设你想要对该地图中的键进行排序(在地图内部或将它们全部添加到某个列表之后)。
However, for sorting lists you have Collections.sort()
which can rely on both natural order (if elements implement Comparable
) or a custom Comparator
. 但是,对于排序列表,您有Collections.sort()
,它可以依赖于自然顺序(如果元素实现Comparable
)或自定义Comparator
。 Also, you can have a look at SortedSet
(and the TreeSet
implementation) if you want to have the order maintained while you add/remove elements. 此外,如果要在添加/删除元素时维护订单,可以查看SortedSet
(和TreeSet
实现)。
For maintaining a map with ordered keys, you have the SortMap
(with a notable implementation: TreeMap
) which will make sure the order it preserved at any moment -- you can add the elements randomly and whenever you iterate you'll get the keys in order. 为了维护带有序键的映射,你有SortMap
(有一个值得注意的实现: TreeMap
),它将确保它随时保留的顺序 - 你可以随机添加元素,每当你迭代时你都会得到密钥订购。 Again the order will can be the natural one (provided by Comparable.compareTo
) or you can provide custom ordering by implementing the Comparator
interface. 同样,顺序可以是自然顺序(由Comparable.compareTo
提供),也可以通过实现Comparator
接口提供自定义顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.