Java比较器从最高到最低排序

问题描述 投票:-2回答:2

嗨,我做了一个数组列表:

ArrayList<String> stringList = new ArrayList<>();

当前存储:

["Joe,d=5", "ken,d=0", "Biden,d=4", "Han,d=5", "Yoyo,d=0"]

比较器从最高到最低我需要什么来比较d=x?像这样:

["Joe,d=5", "Han,d=5", "Biden,d=4", "ken,d=0", "Yoyo,d=0"]
java sorting arraylist comparator
2个回答
0
投票

您可以这样操作。

  • 首先创建一个lambda以提取数字并将其转换为整数。
  • 然后创建一个Comparator并以相反的顺序对字符串进行排序。
List<String> list = Arrays.asList("Joe,d=5", "ken,d=0", "Biden,d=4", "Han,d=5", "Yoyo,d=0");

Function<String,Integer> extract = a->Integer.parseInt(a.substring(a.indexOf("=")+1));

Comparator<String> comp = Comparator.<String>comparingInt(extract::apply).reversed();


Collections.sort(list,comp);

System.out.println(list);

打印

[Joe,d=5, Han,d=5, Biden,d=4, ken,d=0, Yoyo,d=0]


0
投票

尝试一下。假设这些字符串始终具有该格式。

Collections.sort(stringList, 
        (o1, o2) -> 
                Integer.parseInt(o2.split(",")[1].split("=")[1])
                        -Integer.parseInt(o1.split(",")[1].split("=")[1])
);
© www.soinside.com 2019 - 2024. All rights reserved.