Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

BinaryOperator.maxBy(LocalDate::compareTo)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading