How to create a list of String from a list of Object using reduce in Java 8?

Viewed 84

I have an object as follows:

class Order {
  private String code;
  private String status;
  // Constructor, getters and setter and so on
}

I need to create a list of the codes, from a list of orders, which satisfy a condition. I have implemented something similar in JavaScript and it looks like below:

const codes = orders.reduce((codeList, order) => {
  if (order.status === 'NEW') return codeList.push(order.code)
  return codeList
}, [])

Is it possible to achieve this using Java 8?

2 Answers

In Java you should use collect, not reduce, for this purpose:

List<String> codes =
    orders.stream()
          .filter(o -> o.getStatus().equals("NEW"))
          .map(Order::getCode)
          .collect(Collectors.toList());

Reduce is for aggregate values in a single result (like AVG or SUM for example). Collect is used for aggregate values in a collection.

Java 8 Streams are often more efficient than processing on collection because they only process what you need, also allowing you to parallelize if necessary

Bye

Related