[英]In Java, sort hash map by its key.length()
i have a hashmap like this:我有一个这样的哈希图:
HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("java",4);
map.put("go",2);
map.put("objective-c",11);
map.put("c#",2);
now i want to sort this map by its key length, if two keys length are equal (eg go and c# both length 2), then sorted by alphba order.现在我想按它的键长度对这个映射进行排序,如果两个键的长度相等(例如 go 和 c# 的长度均为 2),则按 alphba 顺序排序。 so the outcome i expect to get is something like:
所以我期望得到的结果是这样的:
printed result: objective-c, 11 java, 4 c#, 2 go, 2打印结果:objective-c, 11 java, 4 c#, 2 go, 2
here is my own attamp, but it doesnt work at all...这是我自己的 attamp,但它根本不起作用......
HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("java",4);
map.put("go",2);
map.put("objective-c",11);
map.put("c#",2);
Map<String,Integer> treeMap = new TreeMap<String, Integer>(
new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.length().compareTo(s2.length());
}
}
);
actually the 'compareTo' method appears as red (not be able to compile).... please someone help me with some code example...i am a bit confusing with how to use comparator class to customize compare object...实际上,'compareTo' 方法显示为红色(无法编译)......请有人帮助我一些代码示例......我对如何使用比较器类来自定义比较对象有点困惑......
The compiler is complaining because you cannot call compareTo
on an int
.编译器抱怨,因为你不能在
int
上调用compareTo
。 The correct way to sort the map is the following:对地图进行排序的正确方法如下:
Map<String, Integer> treeMap = new TreeMap<String, Integer>(
new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
if (s1.length() > s2.length()) {
return -1;
} else if (s1.length() < s2.length()) {
return 1;
} else {
return s1.compareTo(s2);
}
}
});
The first two conditions compare the lengths of the two String
s and return a positive or a negative number accordingly.前两个条件比较两个
String
的长度并相应地返回正数或负数。 The third condition would compare the String
s lexicographically if their lengths are equal.如果它们的长度相等,则第三个条件将按字典顺序比较
String
s。
You call String#length()
, which returns a primitive int
.您调用
String#length()
,它返回一个原始int
。 You need the static method Integer.compare(int,int)
.您需要静态方法
Integer.compare(int,int)
。 If you are on Java 8, you can save yourself a lot of typing:如果您使用的是 Java 8,则可以节省大量输入:
Map<String,Integer> treeMap = new TreeMap<>(
Comparator.comparingInt(String::length)
.thenComparing(Function.identity()));
public int compare(String o1, String o2) {
return o1.length() == o2.length() ? o1.compareTo(o2) : o1.length() - o2.length();
}
because length()
doesn't define compareTo
method thats why you see error.因为
length()
没有定义compareTo
方法,这就是您看到错误的原因。 To correct it use Integer.compare(s1.length(), s2.length());
要纠正它使用
Integer.compare(s1.length(), s2.length());
updated code below下面更新了代码
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("java",4);
map.put("go",2);
map.put("objective-c",11);
map.put("c#",2);
Map<String,Integer> treeMap = new TreeMap<String, Integer>(
new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
}
);
treeMap.putAll(map);
System.out.println(treeMap);
}
}
If using the TreeMap is not mandatory
如果使用TreeMap不是强制性的
Explantion : Define a Comaprator
, and next step, define a list so we can add all map entries into a list.说明:定义一个
Comaprator
,下一步,定义一个列表,以便我们可以将所有地图条目添加到列表中。 At the end, sort the list by defined Comaprator
最后,按定义的
Comaprator
对列表进行排序
Code :代码:
Comparator<Map.Entry<String,Integer>> byMapValues =
(Map.Entry<String,Integer> left, Map.Entry<String,Integer> right) ->left.getValue().compareTo(right.getValue());
List<Map.Entry<String,Integer>> list = new ArrayList<>();
list.addAll(map.entrySet());
Collections.sort(list, byMapValues);
list.forEach( i -> System.out.println(i));
Output :输出:
c#=2
go=2
java=4
objective-c=11
Note: get sorted by number注意:按数字排序
if there is need to do comparison based on key, the following line can be used.如果需要基于key做比较,可以使用以下行。
Comparator<Map.Entry<String,Integer>> byMapKeys =
(Map.Entry<String,Integer> left, Map.Entry<String,Integer> right) -> left.getKey().compareTo(right.getKey());
The Comparator should be:比较器应该是:
new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.