user3325783
user3325783

Reputation:

Sorting variables in objects in an ArrayList

I have an ArrayList with 3 Objects in it. Each Object is a new book in my case. Each book has different values for the title, retail price, quantity in stock, etc.

How do I compare and sort the retail price for all of the objects. I have heard of

Collections.sort(books, new Comparator<BookInfo>(){
    @Override
    public int compare(BookInfo book1, BookInfo book2) {
        return book1.getTitle().compareTo(book2.getTitle());
    }
});

with a custom Comparator, but I cannot use the compareTo method for doubles/ints. How would I implements this, or change it so I can compare doubles/ints?

Upvotes: 0

Views: 109

Answers (3)

Warlord
Warlord

Reputation: 2826

You can implement the Comparator however you want, you only need to return a correct value, depending on comparison of the two objects:

  • negative integer if book1 < book2
  • positive integer if book1 > book2
  • 0 if book1 == book2

    Collections.sort(books, new Comparator<BookInfo>() {
        @Override
    
        public int compare(BookInfo book1, BookInfo book2) {
            if (book1.getPrice() < book2.getPrice()) {
                return -1;
            } else if (book1.getPrice() > book2.getPrice()) {
                return 1;
            } else return 0;
        }
    });
    

This way you can customize the behaviour of Comparator anyway you like.

Upvotes: 1

nidomiro
nidomiro

Reputation: 830

try casting to class Double and then compare:

Collections.sort(books, new Comparator<BookInfo>(){

        @Override
        public int compare(BookInfo book1, BookInfo book2) {
            Double p1 = book1.getRetailPrice();
            Double p2 = book2.getRetailPrice();
            return p1.compareTo(p2);
        }
    });

If you want to sort first after Price and second after Name:

Collections.sort(books, new Comparator<BookInfo>(){

        @Override
        public int compare(BookInfo book1, BookInfo book2) {
            Double p1 = book1.getRetailPrice();
            Double p2 = book2.getRetailPrice();
            int res = p1.compareTo(p2);
            if(res == 0){
                return book1.getTitle().compareTo(book2.getTitle());
            }
            return res;
        }
    }); 

Upvotes: 1

Vinay Veluri
Vinay Veluri

Reputation: 6855

You can do this always

Assumption : price value is Double

   Collections.sort(books, new Comparator<BookInfo>(){

    @Override
    public int compare(BookInfo book1, BookInfo book2) {
        return book1.getPrice().compareTo(book2.getPrice());
    }
});

Reference : How to sort an array of ints using a custom comparator?

Upvotes: 2

Related Questions