gpt4 book ai didi

java - 使用分隔列对文件进行排序

转载 作者:行者123 更新时间:2023-12-01 19:51:18 25 4
gpt4 key购买 nike

我有一个以下格式的文件,

Johnny|10|9|6
Smith|1|6|5
Mani|5|3|4
Someone|11|2|12
John|6|10|11

所以,我想在 java 中对这个文件进行排序,我可以使用下面的代码来做到这一点

public class FileComparision {

public static void main(String[] args) throws IOException {
String inputFile = "C:\\testFile\\result1.txt";

FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String inputLine;
List<String> lineList = new ArrayList<String>();
while ((inputLine = bufferedReader.readLine()) != null) {
lineList.add(inputLine);
}
fileReader.close();

Collections.sort(lineList);
}
}

The output will be
John|6|10|11
Johnny|10|9|6
Mani|5|3|4
Someone|11|2|12
Smith|1|6|5

所以,代码工作正常,但这个问题的原因是,我想在不同的列上对这个文件进行排序,因为它是一个 | 分隔符列,我想使用第二或第三或可能是第四,具体取决于用户输入,有什么方法可以实现这一点吗?例如,如果用户想要第三列作为排序主键,那么整个文件的结果与正常情况不同。

最佳答案

只需创建一个代表您输入的模型类(我不确定这些值的含义,因此我只是将它们称为 a、b 和 c - 确实建议使用一些有意义的命名):

public class Person implements Comparable<Person>{

private String name;
private int a;
private int b;
private int c;

public Person(String[] input){
if(input.length < 4)
throw new IllegalArgumentException("Invalid input size!");
name = input[0];
// note: will throw an Exception if the values cannot be represented as ints
a = Integer.parseInt(input[1]);
b = Integer.parseInt(input[2]);
c = Integer.parseInt(input[3]);
}

public String getName() {
return name;
}

public int getA() {
return a;
}

public int getB() {
return b;
}

public int getC() {
return c;
}

@Override
public int compareTo(@NonNull Person another) {
// could be any other property as well
return Integer.compare(this.a, another.a);

然后将您的输入拆分为 String使用 inputLine.split("\\|") 进行数组并创建一个 ArrayList<Person> ,然后调用Collections.sort(yourList)在上面。如果您需要更多指导,请随时发表评论。

编辑:如 azro指出,默认比较器只会按字母顺序对字符串进行排序,请检查 String source code line 1140了解详情。因此,您不能指望 Java 能够正确比较表示为字符串的任意类型。

关于java - 使用分隔列对文件进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51245300/

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