Search code examples
javafilesortingnotepad

Sorting String arrayList alphabetically after word that comes after \t [Java]


I have created a book library in notepad that looks like this :

    Author           | Name of the book | Availability? | Readers Code | Return Date

----------------------------------------------------------------------------
    J. K. Rowling      Harry Potter       Yes             -              -
    Mark Sullivan      The Black Book     Yes             -              -
    Margaret Atwood    Rogue              Yes             -              -

And i need to sort this by name of the books alphabetically. Words are separated by using \t. How can i do that?

This is the code that adds new books :
try (BufferedWriter bw = new BufferedWriter(
                        new FileWriter("C:/Users/Name/Desktop/library.txt", true))) {


                    System.out.print("Enter authors name\t");
                    name = sc.nextLine();
                    name = sc.nextLine();
                    author[l] = name;

                    System.out.print("Enter books name\t");
                    name = sc.nextLine();
                    bookname[l] = name;

                    vaiBib[l] = "Yes";
                    BilNr[l] = "-";
                    AtgDat[l] = "-";

                    l++;

                    if ((author[l- 1] != null) && (bookname[l- 1] != null)) {
                        content = bookname[l- 1] + "\t\t" + author[l- 1] + "\t\t" + vaiBib[l- 1]
                                + "\t\t\t" + BilNr[l- 1] + "\t\t" + AtgDat[l- 1];
                        bw.write(content);
                        bw.newLine();

                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }

And with this code i make linked lists from lines that are in notepad :

BufferedReader br = new BufferedReader(new FileReader("C:/Users/Name/Desktop/library.txt"));
    ArrayList<String> Line2= new ArrayList<>();
                    while ((line = br.readLine()) != null) {
                        Line2.add(line);
                    }

Solution

  • If you can use Java 8:

    Line2.sort(Comparator.comparing(s -> s.substring(s.indexOf('\t') + 1)));
    

    In earlier Java versions you will need to write a Comparator class, you can find numerous examples and tutorials on the Internet. The basic idea of comparing the part of the string that comes after the first tab by taking s.substring(s.indexOf('\t') + 1)) is still valid, you will just need to do it for each of the two strings you are comparing.