Search code examples
javajava-stream

How to optimize java code using the features of java 8


The code below works fine but I want to optimize it and write it in another way.

private List<OrderFeedback> getControlOrderFeedback(List<OrderInner> orderInners){
    List<OrderFeedback> controlResult = new ArrayList();
    if(isTypeDeclaration){
        orderInners.forEach(co -> {
            controlResult.add(OrderFeedback.builder()
                    .result(co.getResult())
                    .code(co.getCode).build()
            );
        });
        return controlResult;
    }
    return null;
}

Solution

  • Not sure what is the bottleneck here but you can rewrite it in a more java-streams fashion like

    private List<OrderFeedback> getControlOrderFeedback(List<OrderInner> orderInners){
        if(!isTypeDeclaration) {
            return null;
        }
        return orderInners.stream()
                   .map(co -> OrderFeedback.builder().result(OrderInner::getResult).code(OrderInner::getCode).build())
                   .collect(Collectors.toList());
    }
    

    Note that the only benefit here is that it won't create new ArrayList() unless it passes the isTypeDeclaration check.