gpt4 book ai didi

java - 按每个字符串中逗号后的值按字母顺序对 ArrayList 进行排序

转载 作者:行者123 更新时间:2023-12-01 06:49:38 28 4
gpt4 key购买 nike

我有一个包含字符串的 ArrayList,如下所示:

  • 项目1:一些文字,安娜贝尔
  • 项目 2:一些文字,詹姆斯
  • 项目3:一些文字,康纳

我想按每个字符串中逗号后面的值按字母顺序对 ArrayList 进行排序。

我怎样才能实现这个目标?

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

// New BufferedReader.
BufferedReader reader = new BufferedReader(new FileReader(
file));

// Add all lines from file to ArrayList.
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
lineList.add(line);
}

// Close it.
reader.close();

// Print each line.
for (String line : lineList) {
System.out.println(line);
}

最佳答案

使用 ComparatorCollections.sort()方法。

例如:

Collections.sort(lineList, new Comparator<String>{
public int compare(String str1, String str2) {
String actual1 = str1.split(",")[1];
String actual2 = str2.split(",")[1];

return actual1.compare(actual2);
}
});

您可能需要某种方法来确保您实际提取字符串的正确部分,以防有零个或多个逗号。例如,您可以将 substring()lastIndexOf() 结合使用,如 IQV 提到的。

关于java - 按每个字符串中逗号后的值按字母顺序对 ArrayList 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41824593/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com