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?
Asked
Active
Viewed 1.1k times
1
-
2Show us your code please. – leopal Apr 17 '19 at 08:07
-
1possible duplicate of [Sort List in reverse order](https://stackoverflow.com/questions/18073590/sort-list-in-reverse-in-order) – Another coder Apr 17 '19 at 08:17
-
1See [a link] https://stackoverflow.com/questions/5894818/how-to-sort-arraylistlong-in-decreasing-order/5894862 – Roman Kolesnikov Apr 17 '19 at 08:17
4 Answers
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:
create a copy:
List<YourType> copy = new ArrayList<>(yourList);
And then sort the
copy
.use streams:
List<YourType> sorted = yourList.stream() .sorted(Comparator.reverseOrder()) .collect(Collectors.toList());
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