1

I have to sort out 15 numbers that are given by a user in descending order. I can write how to sort them in ascending order but I don't know how to turn them. To use for-loop or something else?

Bogdan Avas
  • 19
  • 1
  • 1
  • 2

4 Answers4

6

If you use Java 8 or above you can use this:

yourList.sort(Comparator.reverseOrder());

If you want to keep the initial ordering of the list, you can:

  1. create a copy:

    List<YourType> copy = new ArrayList<>(yourList);
    

    And then sort the copy.

  2. use streams:

    List<YourType> sorted = yourList.stream()
                                    .sorted(Comparator.reverseOrder())
                                    .collect(Collectors.toList());
    
azro
  • 53,056
  • 7
  • 34
  • 70
Lino
  • 19,604
  • 6
  • 47
  • 65
3

You can use that example

List<Integer> list = Arrays.asList(10, 5, 7, 8, 6, 9);
Collections.sort(list, Collections.reverseOrder());
System.out.println(list);

Show: 10, 9, 8, 7, 6, 5

Dred
  • 1,076
  • 8
  • 24
1

Sort the arraylist first then reverse it, like this:

Collections.sort(arraylist);
Collections.reverse(arraylist);
System.out.println(arraylist);
Malekai
  • 4,765
  • 5
  • 25
  • 60
Syed Mehtab Hassan
  • 1,297
  • 1
  • 9
  • 23
0

You can just call Comparator.reverseOrder() for that.

ItFreak
  • 2,299
  • 5
  • 21
  • 45