P
P
pfedorov0310902021-03-16 08:33:47
Java
pfedorov031090, 2021-03-16 08:33:47

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

1 answer(s)
D
Denis Zagaevsky, 2021-03-16
@pfedorov031090

return list.get(0).split(" ")[finalInput].compareTo(list.get(1).split(" ")[finalInput]);

Here is your mistake. The comparator should not know anything about the list at all, try to put it in a separate class, and you will see that it does not work.
What needs to be compared comes as input to the compare method. These are two strings that need to be compared, and you don't use them. Drink them and compare.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question