我得到了一个任务,要对文本文件进行排序,满足以下要求:
并将数据写入另一个文件:
问题在于:
无法正确排序我所需的内容。
以下是输入文件的示例:
期望的输出结果是:
但是,我得到的是:
问题是如何编写适当的排序?谢谢回答。
- 按列排序
- 按第一列排序(如果列中的数据相同,则按第二列排序),行中的数据在排序后保持不变;
- 数字必须按升序排序,字母按字母顺序排序,数字比字母大;
- 列用制表符("\t")分隔。
public class ReadDataFile {
public static List<List<String>> readData(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName + ".txt"));
List<List<String>> data = new ArrayList<List<String>>();
String line;
while (true) {
line = br.readLine();
if (line == null)
break;
List<String>lines = Arrays.asList(line.split("\t"));
data.add(lines);
System.out.println(lines);
}
br.close();
return data;
并将数据写入另一个文件:
public void writeToFile(String fileName) throws IOException {
FileWriter writer = new FileWriter(fileName);
List<List<String>> data = ReadDataFile.readData("input");
Collections.sort(data, new Comparator<List<String>>() {
@Override
public int compare(List<String> o1, List<String> o2) {
// TODO Auto-generated method stub
return o1.get(0).compareTo(o2.get(0));
}
});
for (List<String> lines : data) {
for (int i = 0; i < lines.size(); i++) {
writer.write(lines.get(i));
if (i < lines.size() - 1) {
writer.write("\t");
}
}
writer.write("\n");
}
writer.close();
}
问题在于:
public int compare(List<String> o1, List<String> o2) {
// TODO Auto-generated method stub
return o1.get(0).compareTo(o2.get(0));
}
无法正确排序我所需的内容。
以下是输入文件的示例:
-2.2 2 3 4 329 2
2.2 12345q 69 -afg
2.2 12345q 69 -asdf
-22 1234234 asdfasf asdgas
-22 11 abc
-22 -3 4
-1.1
qqqq 1.1
期望的输出结果是:
-22 -3 4
-22 11 abc
-22 1234234 asdfasf asdgas
-2.2 2 3 4 329 2
-1.1
2.2 12345q 69 -afg
2.2 12345q 69 -asdf
qqqq 1.1
但是,我得到的是:
-1.1
-2.2 2 3 4 329 2
-22 -3 4
-22 11 abc
-22 1234234 asdfasf asdgas
2.2 12345q 69 -afg
2.2 12345q 69 -asdf
qqqq 1.1
问题是如何编写适当的排序?谢谢回答。
"2"
大于"10"
,因为字符被比较,'2'
大于'1'
(同样,"-22"
大于"-2.2"
,因为'2'
和'.'
被比较)。你需要解析这些字符串以获得数字比较(并检查它们是否为数字)。 - ThomasCollections.sort(data, new Comparator<List<String>>() { ... }
。 - ThomasS
比C
更高,所以它排序更靠后。说“数字比字母高”意味着数字在字母之后排序,但是你的示例却相反。请明确语言。另外,字母排序是否区分大小写?重音字母呢?您想按某种语言排序吗?例如,在德语中,ü
与u
排序相同吗? - Andreas