I want to refactor a Java 7 code to Java 8.
Here the Java 7 code:
List<A> aList = new ArrayList<>();
for (B b : bList) {
D d = new D(b.getSomeWhat());
d.setDisabled(true);
aList.add(d);
}
I try this one in Java 8:
bList.stream().map(b -> {
D d = new new D(b.getSomeWhat());
d.setDisabled(true);
}).collect(Collectors.toList());
I have a missisng return statement error.
How can I write the code with Java 8 streams?
Return d in your mapping:
bList.stream().map(b -> {
D d = new D(b.getSomeWhat());
d.setDisabled(true);
return d;
}).collect(Collectors.toList());
There are two problems in your code:
() - {} construct requires return statement,d.setDisabled(true) returns void.You could do something like this:
bList.stream()
.map(B::getSomeWhat)
.map(D::new)
.map(d -> {
d.setDisabled(true);
return d;
}).collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With