Tom
Tom

Reputation: 91

How to add objects to an Array list by alphabetical order of particular variable of object

I have a library program and within that program is a BorrowBookRecord Record class and a Library class. In the library class contains a 'borrowBook()' method that when called and successfully used, creates a BorrowBookRecord object and adds it to an array list of BorrowBookRecords which is stored in the Library class. My only problem is I have absolutely no idea how to get the borrowBook() method to store the records in alphabetical order. I wouldn't even know where to start. Each record has a 'student username' as one of its variables which I want to use to as what determines the objects alphabetical order in the list.

This is the borrow book method in the library class

 public boolean borrowBook(String librarianUsername, String studentUsername, String bookISBN){
    User user = findUserByUsername(studentUsername);

    if(checkPermissionTypeByUserNameBorrow(librarianUsername) && user.isOverBorrow() && checkPermissionTypeByUserNameReserve(studentUsername)){
        if(checkIfAnyAvaliable(bookISBN)){
              for(Book book: books){
                    if(book.getISBNNumber().equals(bookISBN) && book.checkAvaliable()){
                        book.modifyStatus(BookStatus.Reserved);
                        Date date = new Date();

                        BorrowBookRecord record = new BorrowBookRecord(studentUsername, bookISBN, book.getCopyNumber(), date);
                        borrowRecords.add(record);
     /////>>>this is where record is made.
                        user.increaseNumberOfborrowedBooks();
                        break;
                    }
              }                                   
        }
        else{
            throw new IllegalArgumentException("There are no books of that isbn avaliable to borrow");
            }
    }
    else{
        throw new IllegalArgumentException("Student cannot borrow anymore Books/librarian has wrong permissontype");
    }
    return true;
}

Upvotes: 0

Views: 215

Answers (2)

shriyog
shriyog

Reputation: 958

In cases where the elements must be stored in a sorted manner based on some criteria, one must go of TreeSet and not ArrayList.

You can replace your data structure to use Java TreeSet so that after every insertion you would have your elements ordered as per given criterion.

The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

Here, you need to provide a Comparator specific to your ordering requirements. So, to order according to studentUsername you must define your Comparator as -

public class BookComparator implements Comparator<BorrowBookRecord > {
    @Override
    public int compare(BorrowBookRecord o1, BorrowBookRecord o2) {
        return o1.studentUsername.compareTo(o2.studentUsername);
    }    
}

Upvotes: 1

shmosel
shmosel

Reputation: 50726

You can do a binary search with a custom comparator to find the insertion point, as long as you maintain the order:

int index = Collections.binarySearch(borrowRecords, record,
        Comparator.comparing(BorrowBookRecord::getStudentUsername));
if (index < 0) {
    index = -(index + 1);
}
borrowRecords.add(index, record);

Or you can have BorrowBookRecord implement Comparable instead of using a comparator.

Upvotes: 1

Related Questions