I have not used any Java 8.
Here is the code that I wrote below Java 8 Version.
List<GetOrderResponseType> orders = findOrderResponseType.getOrder();
List<GetOrderResponseType> openOrders = new ArrayList<GetOrderResponseType>();
if (!CollectionUtils.isEmpty(orders)) {
for(GetOrderResponseType order : orders ) {
if ( order != null) {
if (order.getOrderSummary() != null) {
if ( order.getOrderSummary().getState() != null) {
if (order.getOrderSummary().getState().toString().toLowerCase().startsWith("open")) {
openOrders.add(order);
}
}
}
}
}
}
return openOrders;
Now, I am trying to change to Java 8 using Streams.
openOrders = orders.stream()
.filter(order -> Objects.nonNull(order))
.map(order -> order.getOrderSummary())
.filter(orderSummary -> Objects.nonNull(orderSummary))
.map(orderSummary -> orderSummary.getState())
.filter(orderSummaryState -> Objects.nonNull(orderSummaryState))
.map(orderSummaryState -> orderSummaryState.toString())
.filter(orderSummaryStateStr -> Objects.nonNull(orderSummaryStateStr))
.filter(orderSummaryStateStr -> orderSummaryStateStr.toLowerCase().startsWith("open"))
.collect(Collectors.toList<GetOrderResponseType>());
on the last statement I am getting Syntax error on token "(", Expression expected after this token.
Thanks, Bandita Pradhan
The .map()
function changes the type of object stored in the stream. For instance, when you do .map(order -> order.getOrderSummary())
you are changing the stream from Stream<GetOrderResponseType>
to Stream<OrderSummary>
. So on your last step when you try to collect the stream back to a List<GetOrderResponseType>
, you can't because you have a Stream<String>
, which is the string order summary state, rather than Stream<GetOrderResponseType>
.
What you are trying to accomplish may be better done with a single filter, and passing in a method reference that does your filtering, like this:
List<GetOrderResponseType> openOrders = orders.stream()
.filter(this::isOpenOrder)
.collect(Collectors.toList());
And then define an isOpenOrder
method as such:
private boolean isOpenOrder() {
if (order == null) {
return false;
}
if (order.getOrderSummary() == null) {
return false;
}
if (order.getOrderSummary().getState() == null) {
return false;
}
return order.getOrderSummary().getState().toString().toLowerCase().startsWith("open");
}