HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Extract last delivery for each name on each date

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lasteachdatenameforextractdelivery

Problem

I've been using Java 8 Stream features quite a lot these days and am very happy with it. I've written a code that uses groupingBy and max but was wondering if it can still be optimized or even just be tweaked for better readability.

Some sample data:

Name, OrderDate, DeliveryTime
abc, 2010-01-15, 2010-01-15T11:00:00
abc, 2010-01-15, 2010-01-31T07:00:00 //should be marked as latest
zzz, 2010-01-15, 2010-01-13T11:00:00
zzz, 2010-01-15, 2010-01-23T07:00:00 //should be marked as latest


Here's the code I've written:

public class DeliveryTest {
   class Delivery {
      String name;
      LocalDate orderDate;
      LocalDateTime deliveryTime;
      boolean isLatest = false;
      //getters and setters here
   }

   @Test
   public void testLatestDelivery() {
      List deliveries = new ArrayList<>();
      //populate the test data here

      //group the deliveries by name and orderDate 
      Map>> groupByNameAndOrderDate = deliveries.stream()
            .collect(groupingBy(Delivery::getName, groupingBy(Delivery::getOrderDate)));

      //find and mark as "Latest" for each of the the max deliveryTime per name and orderDate grouping, 
      groupByNameAndOrderDate.forEach((name, byNameMap) -> {
          byNameMap.forEach((orderDate, byOrderDateList) -> {
              byOrderDateList.stream()
                  .max((n1, n2) -> n1.getDeliveryTime().compareTo(n2.getDeliveryTime())).get()
                  .setIsLatest(true);
          });
      });
      //do assertions here
   }
}


Can this Java 8 code still be improved (for example the part where I have nested forEach)?

Or written shorter but still readable (for example, can the group and max be combined)?

Solution

You could short-hand your max() function with the use of Comparator.comparing()

byOrderDateList.stream()
  .max(Comparator.comparing(Delivery::deliveryTime)).get()
  .setIsLatest(true);

Code Snippets

byOrderDateList.stream()
  .max(Comparator.comparing(Delivery::deliveryTime)).get()
  .setIsLatest(true);

Context

StackExchange Code Review Q#158002, answer score: 4

Revisions (0)

No revisions yet.