Java: Use Stream to sort the contents of the collection

Introduction

Now you want to sort a collection of coordinate classes (x, y). When I was looking for an easy way to do it, it seemed that Stream could be used, so I tried using it.

It was fine until I put it on the console, but when I converted it to a collection after sorting, I got stuck, so I will leave it as a memo.

Implementation

First, create a class of coordinates.

Point.java


public class Point{
    int x;
    int y;            

    Point(int x, int y){
        this.x = x;
        this.y = y;
    } 
        
    //getter
    public int getX(){return x;}
    public int getY(){return y;}
}

Then use Stream to sort the collection of coordinate classes. The contents of the sort are described by the sorted method, and internally compared using the Comparator class. I'm using the thenComparing method to sort x followed by y.

.collect(Collectors.toCollection(ArrayList::new) Finally, I converted it to a collection, but I was really into it here. I thought I could simply use toArrayList.

Main.java


import java.util.ArrayList;
import java.util.Comparator;
import java.util.stream.Stream;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args ) throws Exception {
        ArrayList<Point> node = new ArrayList<Point>();
        
        //Add coordinates to list
        node.add(new Point(4,3));
        node.add(new Point(2,2));
        node.add(new Point(1,3));
        node.add(new Point(1,1));
        node.add(new Point(2,4));
        node.add(new Point(2,1));
        node.add(new Point(5,3));

        //Before Sort
        System.out.println("===Before Sort===");
        node.stream().forEach(nodes -> 
            System.out.println("node X:"+nodes.getX()+" Y:"+nodes.getY()));

        //X:Ascending order, Y:Sort in ascending order and store in ArrayList
        ArrayList<Point> nodeSort = node.stream()
            .sorted(Comparator.comparingInt(Point::getX)   
            .thenComparing(Comparator.comparingInt(Point::getY)))
            .collect(Collectors.toCollection(ArrayList::new));
        
        //After Sort
        System.out.println("===After Sort===");
        nodeSort.stream().forEach(nodes -> 
            System.out.println("node X:"+nodes.getX()+" Y:"+nodes.getY()));
    }
}

Execution result

===Before Sort===
node X:4 Y:3
node X:2 Y:2
node X:1 Y:3
node X:1 Y:1
node X:2 Y:4
node X:2 Y:1
node X:5 Y:3
===After Sort===
node X:1 Y:1
node X:1 Y:3
node X:2 Y:1
node X:2 Y:2
node X:2 Y:4
node X:4 Y:3
node X:5 Y:3

Summary

This time, I've shown you how to sort a collection of classes using Stream. Besides, it seems that you can also extract conditions, so it is quite convenient if you can master Stream.

Recommended Posts

Java: Use Stream to sort the contents of the collection
Use Java lambda expressions outside of the Stream API
[java8] To understand the Stream API
[Java] How to use the HashMap class
Memo: [Java] Check the contents of the directory
[Java] How to use the toString () method
Studying how to use the constructor (java)
[Processing × Java] How to use the loop
[Java] [Maven3] Summary of how to use Maven3
[Processing × Java] How to use the class
How to sort the List of SelectItem
Output of the book "Introduction to Java"
[Processing × Java] How to use the function
[Java] How to use the Calendar class
How to check for the contents of a java fixed-length string
[Java] Contents of Collection interface and List interface
Use jenv to enable multiple versions of Java
JAVA: jar, aar, view the contents of the file
[Java] How to use Thread.sleep to pause the program
I want to var_dump the contents of the intent
Output of how to use the slice method
How to use the replace () method (Java Silver)
[Java] How to get the authority of the folder
Java Welcome to the Swamp of 2D Arrays
Expired collection of java
[Java] How to easily get the longest character string of ArrayList using stream
[Java] How to use compareTo method of Date class
How to write Scala from the perspective of Java
[Java] How to get the maximum value of HashMap
Summary of Java communication API (1) How to use Socket
Summary of Java communication API (3) How to use SocketChannel
Summary of Java communication API (2) How to use HttpUrlConnection
[Rails] How to get the contents of strong parameters
I want to be aware of the contents of variables!
Summary of how to use the proxy set in IE when connecting with Java
[Java] How to use Map
[Java] How to use Map
[Java11] Stream Summary -Advantages of Stream-
How to use java class
[Java] Comparator of Collection class
[Java] How to use Optional ②
[Java] How to use removeAll ()
How to use Java Map
[java] Reasons to use static
How to use Java variables
[Java] Introduction to Stream API
Use Redis Stream in Java
[Java] How to use Optional ①
Input to the Java console
How to use trained model of tensorflow2.0 with Kotlin / Java
[Must-see for apprentice java engineer] How to use Stream API
I tried to summarize the basics of kotlin and java
Get to the abbreviations from 5 examples of iterating Java lists
20190803_Java & k8s on Azure The story of going to the festival
Command to check the number and status of Java threads
[Java] To know the type information of type parameters at runtime
[Ruby] How to retrieve the contents of a double hash
Java: The problem of which is faster, stream or loop
How to derive the last day of the month in Java
How to change the contents of the jar file without decompressing
[Java] Use ResolverStyle.LENIENT to handle the date and time nicely