gpt4 book ai didi

java - 排序 HashMap 及其嵌套的 HashMap

转载 作者:行者123 更新时间:2023-11-29 06:52:01 25 4
gpt4 key购买 nike

我正在尝试对嵌套的 hashMap 进行排序,其中两个 HashMap 都需要进行排序。

第一个hashMap应该是key排序的。第二个应该按值排序。到目前为止,我设法通过制作一个键数组并对其进行排序来对第一个 hashMap 的键进行排序。

我的 hashmap 是这样的

 HashMap<String,HashMap<String,Integer>> carOwners = new 
HashMap<String,HashMap<String, Integer>>();

举个例子,假设我们的第一个字符串是名称、汽车品牌、数量。

例子:大卫:

奥迪>5

宝马>4

伊莎贝尔:

大众>10

MB>4

所以基本上首先我们对名称进行排序,然后我们按值对嵌套的散列进行排序。这怎么能做到...找不到任何有用的信息:(>

最佳答案

要对 Map 进行排序,您可以使用以下类:TreeMap。作为official documentation说,

The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

如果您想按插入顺序对元素进行排序,请使用LinkedHashMap .

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

要按值对 Map 进行排序,请参阅 post .它也适用于 Java7 和 Java8。

希望对您有所帮助。

关于java - 排序 HashMap 及其嵌套的 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44813594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com