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.
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()));
}
}
===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
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