How to sort an arraylist with different data type in java

Cristyan :

I have an arraylist which contains next data : name of an object and some details about him ( let's take as example a book and his price ). So we would have :

  1. Book_Nr1_Name 5
  2. Book_Nr2_Name 8
  3. Book_Nr3_Name 4

Where numbers 5,8,4 represents price of each book. How can i sort this array descending by the price , and get the final output like this :

  1. Book_Nr2_Name 8
  2. Book_Nr1_Name 5
  3. Book_Nr3_Name 4
Jason :

Create an object Book to represent the name and price. Then create a collection of all books. Then we sort by the price using a Comparator that compares Integer values. We then collect to a List since it's sorted.

  static class Book {

        private final String name;

        private final int price;

        Book(String name, int price) {
            this.name = name;
            this.price = price;
        }

        public String getName() {
            return name;
        }

        public int getPrice() {
            return price;
        }
    }
        List<Book> books = Arrays.asList(
                new Book("Book_Nr1_Name", 5),
                new Book("Book_Nr2_Name", 8),
                new Book("Book_Nr3_Name", 4));

        List<Book> sortedByPrice = books.stream()
                .sorted(Comparator.comparingInt(Book::getPrice).reversed())
                .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=349043&siteId=1