Reputation: 605
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?
Upvotes: 1
Views: 1511
Reputation: 11042
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"));
Upvotes: 0