Home > other >  Simplest way to group, collect, and select the max date from a Java stream
Simplest way to group, collect, and select the max date from a Java stream

Time:03-17

I have the following code that takes in a stream of objects, collects them into a hashmap with a key type and a date value that is the maximum date for each type in the list. It works as required but it looks ugly. Is there a way to simplify this code some more? For int objects I can use a comparingInt but in my case I have a LocalDate which doesn't have an equivalent. I tried a groupingBy way but it didn't work. Thanks for any of your suggestions.

import java.time.LocalDate;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toMap;

public class MyClass {
    public static class Match {

  private final String type;
  private final LocalDate day;

  public Match(String type, LocalDate day) {
    this.type = type;
    this.day = day;
  } 

  public String getType() {
    return type;
  }

  public LocalDate getDay() {
    return day;
  }
}
    public static void main(String args[]) {
      Stream stream = Stream.of(new Match("A", LocalDate.of(2019, 10,1)), new Match("A", LocalDate.of(2019,5,1)), new Match("A", LocalDate.of(2019,12,1)), new Match("A", LocalDate.of(2019, 1,1)),
          new Match("B", LocalDate.of(2018,7,1)), new Match("B", LocalDate.of(2018, 8,1)), new Match("B", LocalDate.of(2018,1,1)),
          new Match("C", LocalDate.of(2020,1,1)));
    
    
      System.out.println(stream.collect(toMap(Match::getType, Match::getDay, (a,b) -> a.isAfter(b) ? a : b)));
    }
}

Output:

{A=2019-12-01, B=2018-08-01, C=2020-01-01}

CodePudding user response:

You may try this part for (a,b) -> a.isAfter(b) ? a : b

BinaryOperator.maxBy(LocalDate::compareTo)
  •  Tags:  
  • java
  • Related