订购包含String的Map,但是字符串可能代表一个数字

MDP*_*MDP 1 java

我在Map中有这种值:

Map<Integer, String> map = new HashMap<Integer, String>();                  
map.put(1,"mark");
map.put(2,"1.1");
map.put(3,"google");
map.put(4,"12");
map.put(5,"2.2);
Run Code Online (Sandbox Code Playgroud)

我需要订购此Map,同时订购数字和字符串。

我现在得到的是这个(您可以看到数字不是“有序的”,因为它们是字符串)

1.1
12
2.2
google
mark
Run Code Online (Sandbox Code Playgroud)

我应该得到的是:

1.1
2.2
12
google
mark
Run Code Online (Sandbox Code Playgroud)

我该怎么做?我有点困惑。

Kar*_*cki 5

您不能Map按输入值订购a 。SortedMap例如,TreeMap允许按键对条目进行排序。似乎您使用的是错误的数据结构。

在您的示例中,您可以定义一个将宽大地解析a double并返回Double.NaN而不是异常的函数:

private double lenientParseDouble(String s) {
    try {
        return Double.parseDouble(s);
    } catch (NumberFormatException ex) {
        return Double.NaN;
    }
}
Run Code Online (Sandbox Code Playgroud)

根据Double.compare()文档:

Double.NaN被该方法视为等于其自身并且大于所有其他双精度值(包括Double.POSITIVE_INFINITY)。

然后将其用作Comparator链的一部分

map.values().stream()
        .sorted(Comparator.comparingDouble(this::lenientParseDouble).thenComparing(Function.identity()))
        .forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)