Ace66
Ace66

Reputation: 153

Java init object and set property using Stream

I'm trying to clone a list to a new list and set a property in the new list. I'm trying to use Java8 Stream as it makes cloning simple. My code works but it gives this code smell from Sonar:

Local variables should not be declared and then immediately returned or thrown (squid:S1488)

Is there a way to do this without using a local variable? code:

List<myObject> clonedList = listToClone.stream()
                                                .map(item ->  {
                                                    cloned = new myObject(item);
                                                    cloned.setLifeCycle("someLifeCycle");
                                                    return cloned;
                                                })
                                                .collect(Collectors.toList());

Thanks

Upvotes: 1

Views: 5916

Answers (4)

RoyalBigMack
RoyalBigMack

Reputation: 716

This can be done using Java Stream's .peek()

List<myObject> clonedList = 
listToClone.stream()
.map(myObject::new)
    .peek(x -> x.setLifeCycle("someLifeCycle"))
.collect(Collectors.toList());

Upvotes: 0

Mykhailo Moskura
Mykhailo Moskura

Reputation: 2211

        public class MyObject{
         private String someLifeCycle;
         private Item item;
          public MyObject(final String someLifeCycle,final Item item){
            this.someLifeCycle = someLifeCycle;
            this.item = item;
           }
          //getters and setters
        }

And your code will be like this :

    List<MyObject> clonedList = listToClone.stream()
 .map(item -> new MyObject(item,"someLifeCycle")).collect(Collectors.toList());

Upvotes: 0

ETO
ETO

Reputation: 7269

You can try this:

List<myObject> clonedList = listToClone.stream()
                                       .map(myObject::new)
                                       .map(o -> {
                                           o.setLifeCycle("someLifeCycle");
                                           return o;
                                       })
                                       .collect(Collectors.toList());

Upvotes: 1

It is a warning because you have used a new variable cloned unnecessarily instead of directly chaining functions like

List<myObject> clonedList = listToClone.stream()
    .map(item -> {return (new myObject(item)).setLifeCycle("someLifeCycle");})
    .collect(Collectors.toList());

Upvotes: 1

Related Questions