0

this is how it looks like before sorting. The book title, year publish

enter image description here

I want to sort the title alphabetically then the year published.
This is my current coding for before sorting:

    ArrayList BookList = new ArrayList();
    BufferedReader br = new BufferedReader (new FileReader ("bookInput.txt"));

    String str = br.readLine();
    while (str!=null){
        StringTokenizer st = new StringTokenizer(str,";");
        String title = st.nextToken();
        String yr = st.nextToken();
        int year = Integer.parseInt(yr);
        Book b1 = new Book (title,year);
        BookList.add(b1);
        str = br.readLine();
    }
    br.close();

    //3(d)
    System.out.println("List of Books" + "( " + BookList.size() + " record(s) ) ");
    for (int i = 0; i < BookList.size(); i++){
        Book b2 = (Book)BookList.get(i);
        System.out.println("#" + (i+1) + " " + b2.getTitle() + " , " + b2.getYear());
    }

I've tried everything i know but failed

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
id frn
  • 73
  • 7
  • Make Book implement Comparable – Joakim Danielson Mar 22 '19 at 11:15
  • Use [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) when reading a file to ensure it's properly closed. – Karol Dowbecki Mar 22 '19 at 11:18
  • This can help you [How to sort List of objects by some property](https://stackoverflow.com/questions/5805602/how-to-sort-list-of-objects-by-some-property) – Ricardo Mar 22 '19 at 11:18
  • Possible duplicate of [Java sort ArrayList with custom fields by number and alphabetically](https://stackoverflow.com/questions/18312060/java-sort-arraylist-with-custom-fields-by-number-and-alphabetically) – Sudhir Ojha Mar 22 '19 at 11:20
  • 2
    Possible duplicate of [how sort in java8 list of lists of object by multiple properties](https://stackoverflow.com/questions/54590333/how-sort-in-java8-list-of-lists-of-object-by-multiple-properties) – Vishwa Ratna Mar 22 '19 at 11:20
  • Why do you have `;` as a delimiter in `StringTokenizer` ? Your lines have no `;` symbol – Ruslan Mar 22 '19 at 11:23
  • @Ruslan the ; is to read data from textfiles. the picture shown is from command line, after the data has been transferred to ArrayList called BookList. – id frn Mar 22 '19 at 11:31

1 Answers1

6

You can use the Comparator chain assuming Book class has getters:

BookList.sort(Comparator.comparing(Book::getTitle)
                        .thenComparingInt(Book::getYear));
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • Better mention link of duplicates: https://stackoverflow.com/questions/54590333/how-sort-in-java8-list-of-lists-of-object-by-multiple-properties/54590751#54590751 – Vishwa Ratna Mar 22 '19 at 11:21