Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 对地图进行排序时出现问题_Java - Fatal编程技术网

Java 对地图进行排序时出现问题

Java 对地图进行排序时出现问题,java,Java,我有一张地图 Map<Integer, String> map = new TreeMap<Integer, String>(); map.put(21,"A"); map.put(9,"B"); map.put(23,"C"); map.put(25,"D"); 还是一样的结果 为什么9最后出现它必须是第一个条目。您的比较功能只比较每个数字的最后一位: @Override public int compare(Integer o1, Integer o2) {

我有一张地图

Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(21,"A");
map.put(9,"B");
map.put(23,"C");
map.put(25,"D");
还是一样的结果


为什么9最后出现它必须是第一个条目。

您的比较功能只比较每个数字的最后一位:

@Override
public int compare(Integer o1, Integer o2) {
    return o1 % 10 - o2 % 10; // a number modulo 10 yields it last digit, e.g. 25 % 10 = 5
  }
});
您正在比较(21、9、23、24)的最后几位数字,即(1、9、3、4)。这样,9是最大的数字,因此是列表中的最后一个。

试试这个

 List<Integer> list = new LinkedList(map.keySet());
        Collections.sort(list, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
List List=newlinkedlist(map.keySet());
Collections.sort(list,newcomparator(){
@凌驾
公共整数比较(整数o1,整数o2){
返回o1-o2;
}
});
使用-
%
有什么具体原因吗?这改变了结果的顺序

这是上面的输出


{9=B,21=A,23=C,25=D}

因为9是所有数字中最大的一位!!!您正在比较所有数字的最后一位…因为是您自找的!通过明确说明
%10
,您只保留排序时数字的最后一位。:)真的,这太愚蠢了。顺便说一句,谢谢你的帮助。原来的地图已经分类了。您只能创建保持插入顺序的新有序映射。你想达到什么目标?
@Override
public int compare(Integer o1, Integer o2) {
    return o1 % 10 - o2 % 10; // a number modulo 10 yields it last digit, e.g. 25 % 10 = 5
  }
});
 List<Integer> list = new LinkedList(map.keySet());
        Collections.sort(list, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });