Java – How can I use streams to achieve the same functionality as Java 8

How can I use streams to achieve the same functionality as Java 8… here is a solution to the problem.

How can I use streams to achieve the same functionality as Java 8

What I want to do is add 10 minutes if consecutive orders have the same zip code, otherwise, add 30 minutes to the journey.
For example, if I have a class like the following, this is how I force it to be implemented.

@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 streaming? I tried (reduced) the function but couldn’t understand it.

Solution

You can use IntStream :

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

Related Problems and Solutions