I will write it down because I needed it when solving the AtCoder problem. I think there are several ways to implement it in Java, but I will describe the implementation that I personally feel can be the shortest.
reverseOrder ()
introduced in How to use / create Comparator.Enter the number of numbers to enter and the list of numbers as shown below,
4
2 2 1 3
This is a sample that outputs the input number list in descending order.
Sample.java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import static java.util.Comparator.reverseOrder;
public class Sample {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Long> inputList = new ArrayList<Integer>();
for(int i = 0; i < n ;i++) {
inputList.add(sc.nextInt());
}
//This is the relevant part of the sort
List<Integer> sortedList = inputList.stream().sorted(reverseOrder()).collect(Collectors.toList());
for(int a: sortedList) {
System.out.println(a);
}
}
}
[Updated on September 2, 2020] We received a comment from @swordone. If you want to guarantee immutable, the sort part will be as follows.
List<Integer> sortedList = inputList.stream().sorted(reverseOrder())
.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
Recommended Posts