[英]How to write a custom Comparator for TreeMap in Java?
I want to store key-value pairs in TreeMap and sort the entries based on the value of Key as per following logic: 我想将键值对存储在TreeMap中,并根据以下逻辑基于Key的值对条目进行排序:
Sort by the length of the key. 按键的长度排序。 If the length of two keys is same then sort them alphabetically.
如果两个键的长度相同,则按字母顺序对其进行排序。 Example, for the following key-value pairs.
例如,对于以下键/值对。
IBARAKI MitoCity
TOCHIGI UtunomiyaCity
GUNMA MaehashiCity
SAITAMA SaitamaCity
CHIBA ChibaCity
TOKYO Sinjyuku
KANAGAWA YokohamaCity
The expected output is like this. 预期的输出是这样的。
CHIBA : ChibaCity
GUNMA : MaehashiCity
TOKYO : Sinjyuku
IBARAKI : MitoCity
SAITAMA : SaitamaCity
TOCHIGI : UtunomiyaCity
KANAGAWA : YokohamaCity
You can pass the Comparator as a parameter to Map's constructor. 您可以将Comparator作为参数传递给Map的构造函数。 According to documentation it is used for Keys only:
根据文档,它仅用于密钥:
/**
* Constructs a new, empty tree map, ordered according to the given
* comparator. All keys inserted into the map must be <em>mutually
* comparable</em> by the given comparator: {@code comparator.compare(k1,
* k2)} must not throw a {@code ClassCastException} for any keys
* {@code k1} and {@code k2} in the map. If the user attempts to put
* a key into the map that violates this constraint, the {@code put(Object
* key, Object value)} call will throw a
* {@code ClassCastException}.
*
* @param comparator the comparator that will be used to order this map.
* If {@code null}, the {@linkplain Comparable natural
* ordering} of the keys will be used.
*/
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
In this way you can pass comparator by length of your key like this: 这样,您可以像这样通过密钥的长度传递比较器:
new TreeMap<>(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()))
You can do this as follows. 您可以按照以下步骤进行操作。
public static void main(String[] args) {
Map<String, String> map = new TreeMap<>(new CustomSortComparator());
map.put("IBARAKI", "MitoCity");
map.put("TOCHIGI", "UtunomiyaCity");
map.put("GUNMA", "MaehashiCity");
map.put("SAITAMA", "SaitamaCity");
map.put("CHIBA", "ChibaCity");
map.put("TOKYO", "Sinjyuku");
map.put("KANAGAWA", "YokohamaCity");
System.out.println(map);
}
The CustomSortComparator has been defined as follows. CustomSortComparator的定义如下。
public class CustomSortComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
if (o1.length() > o2.length()) {
return 1;
}
if (o1.length() < o2.length()) {
return -1;
}
return returnCompareBytes(o1, o2);
}
private int returnCompareBytes(String key1, String key2) {
for (int i = 0; i < key1.length() - 1; i++) {
if (key1.charAt(i) > key2.charAt(i)) {
return 1;
}
if (key1.charAt(i) < key2.charAt(i)) {
return -1;
}
}
return 0;
}
}
You need to write your own comparator
for this and use it in TreeMap
, eg: 您需要为此编写自己的
comparator
,并在TreeMap
使用它,例如:
public class StringComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
return s1.length() == s2.length() ? s1.compareTo(s2) : s1.length() - s2.length();
}
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
Map<String, String> map = new TreeMap<>(new StringComparator());
map.put("IBARAKI", "MitoCity");
map.put("TOCHIGI", "UtunomiyaCity");
map.put("GUNMA", "MaehashiCity");
map.put("SAITAMA", "SaitamaCity");
map.put("CHIBA", "ChibaCity");
map.put("TOKYO", "Sinjyuku");
map.put("KANAGAWA", "YokohamaCity");
System.out.println(map);
}
}
This does not handle null
values but you can add the handling if you are expecting null
values in your use case. 这不会处理
null
值,但是如果在用例中期望null
值,则可以添加处理。
You should create a unique comparator for comparing the keys of the map. 您应该创建一个唯一的比较器来比较地图的键。 But because you want to print the values too, you should compare the whole entrysets instead:
但是因为您也想打印这些值,所以应该比较整个条目集:
Comparator<Map.Entry<String, String>> c = new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
int q = Integer.compare(o1.getKey().length(), o2.getKey().length());
return q != 0 ? q : o1.getKey().compareTo(o2.getKey());
}
};
Then you can use this comparator in sorting: 然后可以使用此比较器进行排序:
map.entrySet().stream().sorted(c).forEach(System.out::println);
Instead of converting Map into TreeMap directly you can use this method 您可以使用此方法来代替将Map直接转换为TreeMap
public static Map toTreeMap(Map hashMap)
{
// Create a new TreeMap
Map treeMap = new TreeMap<>(new Comparator<Map.Entry<String, String>>(){
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2 )
{
if (o1.getKey().length() > o2.getKey().length()) {
return 1;
}
if (o1.getKey().length() > o2.getKey().length()) {
return -1;
}
return o1.getKey().compareTo(o2.getKey());
}
});
for(Map.entry e : hashmap){
treeMap.put(e.getKey(),e.getValue);
}
return treeMap;
}
You can define the Comparator<String>
you need in the constructor call to the TreeMap
: 您可以在对
TreeMap
的构造函数调用中定义所需的Comparator<String>
:
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
public class Main {
static final Map<String, String> map =
new TreeMap<String, String> (new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int diff_length = o1.length() - o2.length();
if (diff_length != 0) return diff_length;
return o1.compareTo(o2);
}
});
public static final void main(String[] args) {
map.put("IBARAKI", "MitoCity");
map.put("TOCHIGI", "UtunomiyaCity");
map.put("GUNMA", "MaehashiCity");
map.put("SAITAMA", "SaitamaCity");
map.put("CHIBA", "ChibaCity");
map.put("TOKYO", "Sinjyuku");
map.put("KANAGAWA", "YokohamaCity");
System.out.println(map);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.