gpt4 book ai didi

java - TreeMap 自定义比较器

转载 作者:行者123 更新时间:2023-11-30 10:12:12 26 4
gpt4 key购买 nike

所以我想使用带有自定义比较器的 TreeMap我的键是一个String: id,我的值是一个int: count;我需要比较计数,作为 TREEMAP 中的值(整数)所以我有:

在一个类中:

import java.util.*;

public TreeMap<String, Integer> tm = new TreeMap<String, Integer>(new SortIdCount<Integer>());

在另一个类中:

import java.util.Comparator;

public class SortIdCount implements Comparator<Integer>{

public int compare(Integer count1, Integer count2) {
return count1.compareTo(count2);
}

}

在eclipse中显示错误:

The type SortIdCount is not generic; it cannot be parameterized with arguments <Integer>

最佳答案

The type SortIdCount is not generic; it cannot be parameterized with arguments < Integer >

原因:类别 SortIdCount不是 genric 类型,因此您不能传递 parameterized 参数。行错误:(new SortIdCount<Integer>()

Note : A TreeMap is always sorted based on its keys, however if you want to sort it based on its values then you can build a logic to do this using comparator. Below is a complete code of sorting a TreeMap by values.

按值排序您可以引用下面的代码片段。

import java.util.*;

public class TreeMapDemo {
//Method for sorting the TreeMap based on values
public static <K, V extends Comparable<V>> Map<K, V>
sortByValues(final Map<K, V> map) {
Comparator<K> valueComparator =
new Comparator<K>() {
public int compare(K k1, K k2) {
int compare =
map.get(k1).compareTo(map.get(k2));
if (compare == 0)
return 1;
else
return compare;
}
};

Map<K, V> sortedByValues =
new TreeMap<>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}
public static void main(String args[]) {

TreeMap<String, Integer> treemap = new TreeMap<>();

// Put elements to the map
treemap.put("Key1", 5);
treemap.put("Key2", 4);
treemap.put("Key3", 3);
treemap.put("Key4", 2);
treemap.put("Key5", 1);

// Calling the method sortByvalues
Map sortedMap = sortByValues(treemap);

// Get a set of the entries on the sorted map
Set set = sortedMap.entrySet();

// Get an iterator
Iterator i = set.iterator();

// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
}
}

有关更多详细信息,请参阅此 answer

关于java - TreeMap 自定义比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51998025/

26 4 0
文章推荐: java - 如何在Android中添加向firebase添加数据的进度对话框?
文章推荐: javascript - 选择所有包含 <input> 和
标签的 标签