Sort List in descending order in Java and generate a new List non-destructively

Overview

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.

Correspondence policy

Implementation sample

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

Sort List in descending order in Java and generate a new List non-destructively
[Sort] Sort by following a user, following a follower, and following (descending order)!
[Java8] Sort int type array in descending order using stream
Sort a List of Java objects
Arrylist and linked list difference in java
Generate OffsetDateTime from Clock and LocalDateTime in Java
[Java] [POI] Create a table in Word and start a new line in one cell
When using a list in Java, java.awt.List comes out and an error occurs
How to sort in ascending / descending order with SQLite
[Java] Sort the list using streams and lambda expressions
Write a class in Kotlin and call it in Java
Sort Map values in ascending key order in Java TreeMap
How to convert A to a and a to A using AND and OR in Java
What's new in Java 8
Get location information in Rails and sort in ascending order
What's new in Java 9,10,11
[Java, stream] Sort object list in Japanese by property name
I want to make a list with kotlin and java!
Same judgment / equal value judgment / comparison / order in Swift and Java
How to develop and register a Sota app in Java
Sorting in ascending order in Java (bubble sort: simple exchange algorithm)
Generate AWS Signature V4 in Java and request an API
[Neta] Sleep Sort in Java
Find a subset in Java
List aggregation in Java (Collectors.groupingBy)
Java List Group, Sort, etc.
Create a named Skip List like redis sorted set in Java
[Java] Get the dates of the past Monday and Sunday in order
I tried to sort the data in descending order, ascending order / Rails
How to create a new Gradle + Java + Jar project in Intellij 2016.03
Java Two Lists are ignored in order, null is ignored, and duplicates are ignored.
I wrote a Stalin sort that feels like a mess in Java
[Java] Let's create a mod for Minecraft 1.16.1 [Add and generate trees]
Cast an array of Strings to a List of Integers in Java
[Java] Let's create a mod for Minecraft 1.14.4 [9. Add and generate trees]
Install Rails in the development environment and create a new application
[Java] Let's create a mod for Minecraft 1.14.4 [8. Add and generate ore]
3 Implement a simple interpreter in Java
I created a PDF in Java.
Encoding and Decoding example in Java
Create a new app in Rails
Java 9 new features and sample code
Generate CloudStack API URL in Java
StringBuffer and StringBuilder Class in Java
A simple sample callback in Java
List of members added in Java 9
Sort in List, for personal notes
Understanding equals and hashCode in Java
Get stuck in a Java primer
List of types added in Java 9
Hello world in Java and Gradle
How to test a private method in Java and partially mock that method
Specify the order in which configuration files and classes are loaded in Java
Creating a project (and GitHub repository) using Java and Gradle in IntelliJ IDEA
The story of forgetting to close a file in Java and failing
A note on the differences between interfaces and abstract classes in Java
I wrote a Lambda function in Java and deployed it with SAM
[Java] Generate a narrowed list from multiple lists using the Stream API
Have a tool to create and open a new canvas in Mac preview
Let's create a TODO application in Java 9 Create TODO display Sort by date and time + Set due date default to today's date