我是Java的新手,经常发现我需要对Map<Key, Value>值进行排序.
由于值不是唯一的,我发现自己将其转换keySet为a array,并通过数组排序对该数组进行排序,并使用自定义比较器对与键关联的值进行排序.
有没有更简单的方法?
我们如何排序HashMap<key, ArrayList>?
我想根据一个值来排序ArrayList.
我有一个像下面这样的hashmap
Map<String, List<String>> map = new HashMap<>();
map.put("USA", Arrays.asList("CA","IA","IL"));
map.put("India", Arrays.asList("MUM","CAL"));
map.put("Canada", Arrays.asList("TOR"));
Run Code Online (Sandbox Code Playgroud)
我想根据值中升序排列的列表大小对地图进行排序.我该怎么做.有没有很好的方法呢?
我有一个与此类似的 HashMap:
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(3, 2);
map.put(7, 2);
map.put(5, 1);
map.put(10, 4);
Run Code Online (Sandbox Code Playgroud)
我需要先按值排序,然后按键排序,以防多个键共享相同的值。
结果应如下所示:
(5, 1)
(3, 2)
(7, 2)
(10, 4)
Run Code Online (Sandbox Code Playgroud)
请问有什么建议吗?
我首先比较值,仅在出现重复值的情况下才比较键。所以我同时使用键和值,而不仅仅是值。
我正在尝试HashMap使用LinkedHashMap和排序输出TreeMap.
当我用它TreeMap来理清HashMap它就像一个魅力.
Map<Integer, String> hMap = new HashMap<Integer, String>();
hMap.put(40, "d");
hMap.put(10, "a");
hMap.put(30, "c");
hMap.put(20, "b");
System.out.println(" ");
System.out.println("before");
for (Map.Entry m1 : hMap.entrySet()) {
System.out.print(m1.getKey() + " " + m1.getValue() + " ");
}
System.out.println("after");
Map<Integer, String> hTree = new TreeMap<Integer, String>(hMap);
for (Map.Entry m2 : hTree.entrySet()) {
System.out.print(m2.getKey() + " " + m2.getValue() + " ");
}
Run Code Online (Sandbox Code Playgroud)
输出:before
20 b 40 d 10 a 30 c …
java ×5
hashmap ×3
sorting ×3
collections ×2
dictionary ×2
java-8 ×1
java-stream ×1
treemap ×1