Sort by multiple conditions using Java Stream

Recently, I've been writing Java for the first time in half a year. I used to use ** Java7 (!) ** in my business, but now I'm using Java8.

I use stream quite often, and I wrote it down because I learned the other day that it can be sorted by multiple conditions.

Java Stream API Stream (Java Platform SE 8 )

API that supports aggregation operations such as iterative processing and parallel processing.

By combining with a lambda expression (arrow function in JS), it can be described simply without using extended for syntax.

Sort by multiple conditions

This is possible by using the Comparator interface.

Sorting by multiple conditions is possible by specifying the sorting condition by the comparing () and thenComparing () methods and passing it to sorted () of stream.

Sample code

Please forgive me for the complexity of the design.

ʻArticle` class

Article.java


import java.time.LocalDate;

public class Article {

  /**Contributor*/
  private String contributor;

  /**Posted date*/
  private LocalDate date;

  /**Number of likes*/
  private int goodCount;

  /**constructor*/
  public Article(String contributor, LocalDate date, int goodCount) {
    this.contributor = contributor;
    this.date = date;
    this.goodCount = goodCount;
  }

  /** Getter, Setter */
  public String getContributor() {
    return this.contributor;
  }

  public void setContributor(String contributor) {
    this.contributor = contributor;
  }

  public LocalDate getDate() {
    return this.date;
  }

  public void setDate(LocalDate date) {
    this.date = date;
  }

  public int getGoodCount() {
    return this.goodCount;
  }

  public void setGoodCount(int goodCount) {
    this.goodCount = goodCount;
  }

}

Stream class

Stream.java


import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

public class Stream {
  public static void main(String[] args) {
    //Data generation
    Article a1 = new Article("Taro", LocalDate.of(2018, 7, 11), 15);
    Article a2 = new Article("Taro", LocalDate.of(2015, 11, 1), 53);
    Article a3 = new Article("Taro", LocalDate.of(2015, 10, 31), 54);

    Article a4 = new Article("Hanako", LocalDate.of(2017, 2, 5), 53);
    Article a5 = new Article("Hanako", LocalDate.of(2016, 11, 1), 160);
    Article a6 = new Article("Hanako", LocalDate.of(2012, 8, 20), 22);

    Article a7 = new Article("Pochi", LocalDate.of(2013, 3, 16), 38);
    Article a8 = new Article("Pochi", LocalDate.of(2011, 9, 25), 200);
    Article a9 = new Article("Pochi", LocalDate.of(2018, 4, 13), 10);

    //List creation
    List<Article> list = Arrays.asList(a1, a2, a3, a4, a5, a6, a7, a8, a9);
    list.stream().forEach(a ->
      System.out.println(a.getContributor() + " " + a.getDate() + " " + a.getGoodCount()));

  }
}

For the time being, if you output a list of ʻa1 to ʻa9

Output result


Taro 2018-07-11 15
Taro 2015-11-01 53
Taro 2015-10-31 54
Hanako 2017-02-05 53
Hanako 2016-11-01 160
Hanako 2012-08-20 22
Pochi 2013-03-16 38
Pochi 2011-09-25 200
Pochi 2018-04-13 10

Will be.

Sorting

sorted (Java Platform SE 8)

Pass Comparator as an argument and sort in the specified order.

Sort by single item

Sort by name in a dictionary.

Stream.java


//Comparator creation
Comparator<Article> comparator = Comparator.comparing(Article::getContributor);
//Sort by poster name
list.stream().sorted(comparator)
  .forEach(a ->
    System.out.println(a.getContributor() + " " + a.getDate() + " " + a.getGoodCount()));

Output result


Hanako 2017-02-05 53
Hanako 2016-11-01 160
Hanako 2012-08-20 22
Pochi 2013-03-16 38
Pochi 2011-09-25 200
Pochi 2018-04-13 10
Taro 2018-07-11 15
Taro 2015-11-01 53
Taro 2015-10-31 54

You can also sort by other items.

thenComparing thenComparing (Java Platform SE 8)

A method that allows you to chain comparison conditions. Use as follows.

comparator


Comparator.comparing(...).thenComparing(...).thenComparing(...);

If the previous conditions are the same (ʻequals`), make a further comparison.

Returns a lexicographic order comparator with the other comparator. If this Comparator considers the two elements to be equal (that is, compare (a, b) == 0), then other is used to determine the order.

Sort by multiple items

Sort by name-> post date

Stream.java


//Comparator creation
Comparator<Article> comparator =
  Comparator.comparing(Article::getContributor).thenComparing(Article::getDate);
//Sorting
list.stream().sorted(comparator)
  .forEach(a ->
    System.out.println(a.getContributor() + " " + a.getDate() + " " + a.getGoodCount()));

Output result


Hanako 2012-08-20 22
Hanako 2016-11-01 160
Hanako 2017-02-05 53
Pochi 2011-09-25 200
Pochi 2013-03-16 38
Pochi 2018-04-13 10
Taro 2015-10-31 54
Taro 2015-11-01 53
Taro 2018-07-11 15

Name-> Sort by Likes

Stream.java


//Comparator creation
Comparator<Article> comparator =
  Comparator.comparing(Article::getContributor).thenComparing(Article::getGoodCount);
//Sorting
list.stream().sorted(comparator)
  .forEach(a ->
    System.out.println(a.getContributor() + " " + a.getDate() + " " + a.getGoodCount()));

Output result


Hanako 2012-08-20 22
Hanako 2017-02-05 53
Hanako 2016-11-01 160
Pochi 2018-04-13 10
Pochi 2013-03-16 38
Pochi 2011-09-25 200
Taro 2018-07-11 15
Taro 2015-11-01 53
Taro 2015-10-31 54

If you want to sort in ascending order, add reversed ()

Stream.java


//Comparator creation
Comparator<Article> comparator =
  Comparator.comparing(Article::getContributor).thenComparing(Article::getGoodCount).reversed();
//Sorting
list.stream().sorted(comparator)
  .forEach(a ->
    System.out.println(a.getContributor() + " " + a.getDate() + " " + a.getGoodCount()));

Output result


Taro 2015-10-31 54
Taro 2015-11-01 53
Taro 2018-07-11 15
Pochi 2011-09-25 200
Pochi 2013-03-16 38
Pochi 2018-04-13 10
Hanako 2016-11-01 160
Hanako 2017-02-05 53
Hanako 2012-08-20 22

Impressions

reference

Stream (Java Platform SE 8 ) Comparator (Java Platform SE 8 )

Recommended Posts

Sort by multiple conditions using Java Stream
[Java] Sort by multiple keys while considering null
Bubble sort using ArrayList (JAVA)
[Java8] Sort int type array in descending order using stream
Specify multiple sort conditions in Swift
I tried using Java8 Stream API
Concatenate strings returned by methods of multiple objects in Java Stream
Try using the Stream API in Java
Sort by multiple fields in the class
[Java] Generate a narrowed list from multiple lists using the Stream API
java bubble sort
[JAVA] Stream type
Java Stream API
java selection sort
Studying Java 8 (Stream)
Java8 Stream duplicate check (write neatly using Collector)
java insertion sort
Java Stream termination
[Java] How to operate List using Stream API
[Java] Stream processing
Java 9 Optional :: stream
Studying java8 (such as reading a file using Stream)
[Java] Sort the list using streams and lambda expressions
Java: Use Stream to sort the contents of the collection
[Java] Development with multiple files using package and import
[java] sort in list
[Java] Stream Collectors notes
[Java] Stream API-Stream generation
[Java] Stream API / map
Java string multiple replacement
Java Japanese (Kanji) Sort
Scraping practice using Java ②
Java8 Stream API practice
Java8 Stream reduction operation
Scraping practice using Java ①
Java8 Stream Rough Summary
Note No.5 "HashMap value has multiple values using class" [Java]
Using multiple versions of Java with Brew on Mac + jEnv