generics - 如何将我的 SortedSet 转换为带有 while 循环的 Map?
问题描述
在以下方法中,我按值对 TreeMap 进行排序......现在我想将 SortedSet 中的条目添加到地图中。
static <K, V extends Comparable<? super V>>
SortedSet<Map.Entry<K, V>> entriesSortedByValues(Map<K, V> map) {
SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<Map.Entry<K, V>>(
new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
return res != 0 ? res : 1;
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
解决方案
这个方法会做
static <K, V> Map<K, V> toMap(Collection<Map.Entry<K, V>> coll) {
Map<K, V> map = new LinkedHashMap<>();
for (Map.Entry<K, V> e : coll) {
map.put(e.getKey(), e.getValue());
}
return map;
}
map
您可以在此处为变量使用任何映射。但是由于您之前对条目进行了排序,您可能希望保留顺序。那么LinkedHashMap
将是一个不错的选择。也许您想在界面中表达这一点并改为编写:
static <K, V> LinkedHashMap<K, V> toMap(Collection<Map.Entry<K, V>> coll) {
请注意,您Comparator
的无效。这必须始终正确,但不是:
comparator.compare(e, e) == 0
推荐阅读
- c# - 必须遵守不返回任务的接口 - 必须使用异步库
- java - 无法通过java中的QueryBuilder将json插入cassandra
- plsql - gsource_nm VARCHAR2(1024) := '$Source: /var/opt/pat/iisi/src/plsql/p_autoeph_hpe.sql,v $';
- python - python xlrd属性错误
- docker - 在 docker 容器中找不到文件
- c++ - TensorFlow c++ API 在 session->run() 上崩溃
- r - 是否可以定义内容根文件夹?
- javascript - 根据输入值更改 href 目标
- jasper-reports - 当我尝试传递我的报告连接时,为什么我无法转换为 net.sf.jasperreports.engine.JRDataSource?
- python - 为给定位置创建房地产价格指数