我正在逐行读取文件,我需要按字母顺序对行进行排序,例如,在下面的示例中,它应按每个单词的首字母排序并输出。我坚持如何按字母顺序将每个单词的第一个字符排序,并保留每个单词前面的数字。任何帮助表示赞赏。预先感谢。
output: 567 cat
123 dog
FILE2 = "123 dog\n567 cat\n";
String args[] = {"-a", "5", inputFile.getPath()};
String expected = 567 cat
123 dog
我尝试阅读行和排序,但是它首先根据数字排序。
if (arguments.equals("-a")) {
List<String> lines = Files.readAllLines((Paths.get(filename)));
List<String> matchedLines = lines.stream().sorted()
.collect(Collectors.toList());
答案 0 :(得分:2)
您可以执行以下操作(请注意,我没有在文件中放入任何内容,就像您已经做过的那样,很容易从文件中取出字符串)。以下代码假定您从文件中获取了字符串:
public static void main(String[] args) {
//what we have got from file
String text = "123 dog\n567 cat\n";
//split text to substrings by new line
String[] splitted = text.split("\n");
// create treemap and sort it from greatest to lowest number
Map<Integer, String> mapOfStrings = new TreeMap<Integer, String>().descendingMap();
//put all substrings into our map, following assumes a form that first substring is a text and second substring is an integer
for (int i = 0; i < splitted.length; i++) {
mapOfStrings.put(Integer.valueOf(splitted[i].substring(0, splitted[i].indexOf(" "))), splitted[i].substring(splitted[i].indexOf(" "), splitted[i].length()));
}
//iterate thru map, for each entry in it print its key and value in single line
for (Map.Entry<Integer, String> entry : mapOfStrings.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
更新2:
如果您想按字母(从a到z)排序,则下面的代码就足够了:
public static void main(String[] args) {
String text = "123 dog\n567 cat\n4 zebra\n1983 tiger\n1 lion\n383 turtle";
String[] splitted = text.split("\n");
System.out.println(Arrays.asList(splitted));
Map<String, Integer> mapOfStrings = new TreeMap<String, Integer>();
for (int i = 0; i < splitted.length; i++) {
mapOfStrings.put(splitted[i].substring(splitted[i].indexOf(" "), splitted[i].length()),Integer.valueOf(splitted[i].substring(0, splitted[i].indexOf(" "))));
}
for (Map.Entry<String, Integer> entry : mapOfStrings.entrySet()) {
System.out.println(entry.getValue()+ " " + entry.getKey());
}
}