Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor for-loop with side effects to stream

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?

like image 705
emoleumassi Avatar asked Jan 20 '26 16:01

emoleumassi


2 Answers

Return d in your mapping:

bList.stream().map(b -> {
    D d = new D(b.getSomeWhat());
    d.setDisabled(true);
    return d;
}).collect(Collectors.toList());
like image 172
MBec Avatar answered Jan 22 '26 05:01

MBec


There are two problems in your code:

  1. using () - {} construct requires return statement,
  2. 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());
like image 25
alobodzk Avatar answered Jan 22 '26 06:01

alobodzk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!