Answer the question
In order to leave comments, you need to log in
Sort the list of String by the given word in the string. How to write a comparator?
It is necessary to read several lines from a file, sort them by the word (in alphabetical order), the number of which will be entered by the user. Sorting does not work, I do not understand how to write a comparator by word.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.*;
public class Main {
public static void main(String[] args) {
String path = "src/text";
String outSort1 = "src/output1";
String line = "";
int input = 0;
Scanner scn = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader(path));
while((line = br.readLine()) != null){
list.add(line);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Введите номер слова для сортировки: ");
input = scn.nextInt();
int finalInput = input;
Collections.sort(list, new Comparator<String>() {
public int compare(String o1, String o2) {
return list.get(0).split(" ")[finalInput].compareTo(list.get(1).split(" ")[finalInput]);
}
});
write(list, outSort3);
}
public static void write (ArrayList<String> list, String path) {
try {
PrintWriter printWriter = new PrintWriter(path);
for (int i = 0; i < list.size(); i++) {
printWriter.println(list.get(i));
printWriter.flush();
}
printWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Answer the question
In order to leave comments, you need to log in
return list.get(0).split(" ")[finalInput].compareTo(list.get(1).split(" ")[finalInput]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question