id frn
id frn

Reputation: 73

How to sort ArrayList alphabetically then by number

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 😅

Upvotes: 0

Views: 93

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44942

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

BookList.sort(Comparator.comparing(Book::getTitle)
                        .thenComparingInt(Book::getYear));

Upvotes: 6

Related Questions