javajava-8java-stream

How can I calculate a total value based on whether adjacent elements have the same post code in Java 8 using streams?


What I wanted to do was to add 10min if consecutive orders have the same postcode, otherwise, add 30 min to the journey. For example, if I have a class like the following this is how i achieve that imperatively.

@Data
@AllArgsConstructor
public static class Order{
    private String orderNumber;
    private final String postCode;
}

Order order1 = new Order("1","N1");
Order order2 = new Order("2","N1");
Order order3 = new Order("3","N3");
Order order4 = new Order("4","N4");

List<Order> orders = List.of(order1, order2, order3, order4);

int totalMin = 0;
for (int i=0;i < orders.size()-1 ; i++ ){
  if (orders.get(i+1).getPostCode().equals(orders.get(i).getPostCode())){
      totalMin+=10;
    }
  else{
      totalMin+=30;
  }
}

System.out.println(totalMin) // 70
// if order 2 is new Order("2","N2"); // 90

How can I achieve the same thing, or convert the above using Java 8 streams? I tried the reduce function but couldn't get my head around it.


Solution

  • You could use IntStream for that :

    int totalMin =
    IntStream.range(0, orders.size()-1)
             .map(i-> orders.get(i+1).getPostCode().equals(orders.get(i).getPostCode()) ? 10 : 30)
             .sum();