[英]Please how do I sort map elements based on values in ascending order in java?
我正在尝试使用Collections.sort()对地图元素(基于值)进行排序。 问题是我的程序将元素按降序排序,而不是按升序排序。 如何按升序排序? 下面是我的代码。
package hashTableRR;
import java.util.*;
import java.util.Map.Entry;
public class OrderByValue {
public static void main(String [] args){
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 4);
map.put(2, 6);
map.put(3, 1);
map.put(4, 1);
map.put(6, 8);
map.put(7, 5);
Set<Entry<Integer, Integer>> set = map.entrySet();
List<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>()
{
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2){
return(o2.getValue()).compareTo(o1.getValue());
}
}
);
System.out.println("Keys\t\tValues");
for(Map.Entry<Integer, Integer> entry:list)
{
System.out.println(" "+entry.getKey()+"\t\t "+entry.getValue());
}
}
}
只需在您的compare
函数中更改变量的顺序
return(o1.getValue()).compareTo(o2.getValue());
您的Comparator#compare
实现中可能存在此问题。
您正在返回: o2.getValue().compareTo(o1.getValue())
对于升序,您应该返回: o1.getValue().compareTo(o2.getValue())
如果o1 < o2
,则将生成负值;如果相等,则将生成0
如果o2 > o1
,则将生成正值。
请在此处参阅一些含糊的文档。
以下是在Java中执行Integer
的比较时,可以期望Comparator
返回哪些值的完整见解( 此处提供完整文档):
如果此Integer等于参数Integer,则值为0;否则为0。 如果此Integer在数值上小于参数Integer,则返回小于0的值; 如果此Integer在数值上大于参数Integer(有符号比较),则该值大于0。
只需使用:
return(o1.getValue()).compareTo(o2.getValue());
显然会反序
Map<Integer, Integer> unsortedMap = new HashMap<>();
Map<Integer, Integer> sortedMap = new LinkedHashMap<>();
unsortedMap.put(1, 4);
unsortedMap.put(2, 6);
unsortedMap.put(3, 1);
unsortedMap.put(4, 1);
unsortedMap.put(6, 8);
unsortedMap.put(7, 5);
unsortedMap.entrySet().
stream().
sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed()).
forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
System.out.println(sortedMap);
如果
LinkedHashMap
将键插入Map
的顺序存储数据,请使用LinkedHashMap
。HashMap
不保证任何顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.