Java LinkedHashMap按值排序
我正在尝试找到一个类似于LinkedHashMap的结构,它根据其值对其进行排序。 我需要能够更新这些值。 我会经常检查顺序,所以我需要一个解决方案,避免每次对地图排序 大概是这样的:Java LinkedHashMap按值排序,java,sorting,hashmap,linkedhashmap,Java,Sorting,Hashmap,Linkedhashmap,我正在尝试找到一个类似于LinkedHashMap的结构,它根据其值对其进行排序。 我需要能够更新这些值。 我会经常检查顺序,所以我需要一个解决方案,避免每次对地图排序 大概是这样的: DynamicSortedMap<String,Integer> map = new DynamicSortedMap<String,Integer>(); map.put("key1",4); map.put("key2",3); map.put("key3",6); System.ou
DynamicSortedMap<String,Integer> map = new DynamicSortedMap<String,Integer>();
map.put("key1",4);
map.put("key2",3);
map.put("key3",6);
System.out.println("Map: "+map);
map.update("key1",1);
System.out.println("Update:"+map);
有什么结构允许这样做吗?
如果没有,有什么办法吗
感谢您的帮助,我想您正在寻找类似TreeMap的东西,它按键排序:
SortedMap<String, Integer> map = new TreeMap<String, Integer>();
SortedMap=newtreemap();
尽管LinkedHashMap实际上可能是一个很好的基础,但不幸的是,它在操作迭代顺序方面非常有限。我想你最好用上。类SortValueMap扩展了HashMap{
class SortValueMap extends HashMap<String,Integer>{
@Override
public Set<Entry<String,Integer>> entrySet() {
List<Entry<String,Integer>> entries = new ArrayList<Entry<String,Integer>>(super.entrySet());
Collections.sort(entries, new Comparator<Entry<String,Integer>>(){
@Override
public int compare(Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}});
return new LinkedHashSet<Entry<String,Integer>>(entries);
}
}
...
SortValueMap map = new SortValueMap();
map.put("key1",4);
map.put("key2",3);
map.put("key3",6);
map.put("key4",1);
System.out.println("Map: "+map);
@凌驾
公共集入口集(){
列表条目=新的ArrayList(super.entrySet());
Collections.sort(条目,新的Comparator(){
@凌驾
公共整数比较(Map.Entry o1,Map.Entry o2){
返回o1.getValue().compareTo(o2.getValue());
}});
返回新的LinkedHashSet(条目);
}
}
...
SortValueMap=新的SortValueMap();
地图放置(“键1”,4);
地图放置(“键2”,3);
地图放置(“键3”,6);
地图放置(“键4”,1);
System.out.println(“Map:+Map”);
ALinkedHashMap
按插入顺序排序,而不是按值排序。你要找的是,我同意TreeMap的建议。LinkedHashMap的哪些特性让您选择它而不是其他地图?TreeMap
是按键排序的(但我认为OP希望它是这样的)。:)尝试使用final SortedMap st=new TreeMap()代码>我需要按值排序,并且能够更新不同的元素(如果没有其他解决方案,我可以删除元素并用新值重新插入)
class SortValueMap extends HashMap<String,Integer>{
@Override
public Set<Entry<String,Integer>> entrySet() {
List<Entry<String,Integer>> entries = new ArrayList<Entry<String,Integer>>(super.entrySet());
Collections.sort(entries, new Comparator<Entry<String,Integer>>(){
@Override
public int compare(Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}});
return new LinkedHashSet<Entry<String,Integer>>(entries);
}
}
...
SortValueMap map = new SortValueMap();
map.put("key1",4);
map.put("key2",3);
map.put("key3",6);
map.put("key4",1);
System.out.println("Map: "+map);