Java:按字符串中包含的数字排序字符串列表(降序)

时间:2017-03-20 00:52:10

标签: java sorting substring

我有一个.txt文件的人名和他们在游戏中取得的分数,例如。

2 John
6 Matt
etc.

我正在尝试按照得分最高的人(他们名字旁边的数字)的顺序组织他们。我可以使用substring来获取整数,然后使用Collections.sort,但后来我不确定如何将其与名称联系起来。

如果有人有任何聪明的想法,请帮忙!我目前拥有它所以所有得分/名称都被读入ArrayList,例如:{2 John, 3 Matt}

1 个答案:

答案 0 :(得分:0)

您可以简单地实现自定义Comparator<String>并在第一个空格上拆分(将拆分限制为2)。我还假设应该通过词汇(按字母顺序)排序。像,

List<String> al = new ArrayList<>(Arrays.asList("2 John", //
        "3 Matt", "3 Adam Smith"));
al.sort(new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        String[] a = o1.split("\\s+", 2); // <-- split on white space, limit 2.
        String[] b = o2.split("\\s+", 2);
        int r = Integer.compare(Integer.parseInt(a[0]), //
                Integer.parseInt(b[0]));
        if (r != 0) {
            return -r;
        }
        return a[1].compareTo(b[1]);
    }
});
System.out.println(al);

哪些输出(我认为你想要的)

[3 Adam Smith, 3 Matt, 2 John]
相关问题