1

I have the following POJO:

public class Order {
  private String name;
  private String status;
  private BigDecimal total;

  // getters, setters and ctors down here

}

I am looping through a List<Order> and trying to update all their status fields to a value of "ORDERED". The old (pre Streaming API) way of doing this was:

for (Order order : orders) {
  order.setStatus("ORDERED");
}

I'm trying to figure out the Java 8 ("Streaming") way of accomplishing the same thing. My best attempt thus far:

orders.stream().map(order -> order.setStatus("H"));

Produces a compiler error:

"Incompatible types. Required List but 'map' was inferred to Stream: no instance(s) of type variable(s) R exist so that Stream conforms to List"

Any ideas where I'm going awry?

2
  • Don't use streams for mutating the object while streaming the collection. Commented Jul 17, 2019 at 14:36
  • 2
    You want to perform an action for each element, so what made you decide for trying map instead of one of the other stream operations, e.g. forEach? Commented Jul 17, 2019 at 14:41

2 Answers 2

3

Use forEach:

orders.forEach(order -> order.setStatus("H"));
Sign up to request clarification or add additional context in comments.

Comments

0

You do not want to use Stream.map() because it requires a return value which replaces the original value in the stream. You are also missing a terminal operation in your stream, so even if you fix that by returning the original value it wont work. Stream.forEach() is a terminal operation you can use for this.

To update each object in your list you can just use orders.forEach(). This is the same as orders.stream().forEach().

orders.forEach(o -> o.setStatus("H"));

If you want to update only some values of your List you can use Stream.filter() before:

orders.stream()
        .filter(o -> "ABC".equals(o.getName())
        .forEach(o -> o.setStatus("H"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.