Java 初始化对象并使用 Stream 设置属性

问题描述 投票:0回答:4

我正在尝试将列表克隆到新列表并在新列表中设置属性。 我正在尝试使用 Java8 Stream,因为它使克隆变得简单。 我的代码可以工作,但它从声纳中发出了代码味道:

局部变量不应声明后立即返回或抛出(squid:S1488)

有没有办法在不使用局部变量的情况下做到这一点? 代码:

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

谢谢

java dictionary collections java-8 java-stream
4个回答
1
投票

这是一个警告,因为您不必要地使用了新变量

cloned
,而不是像

这样直接链接函数
List<myObject> clonedList = listToClone.stream()
    .map(item -> {return (new myObject(item)).setLifeCycle("someLifeCycle");})
    .collect(Collectors.toList());

1
投票

你可以试试这个:

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

0
投票
        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
        }

你的代码将是这样的:

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

0
投票

这可以使用 Java Stream 的 .peek() 来完成

List<myObject> clonedList = 
listToClone.stream()
.map(myObject::new)
    .peek(x -> x.setLifeCycle("someLifeCycle"))
.collect(Collectors.toList());
© www.soinside.com 2019 - 2024. All rights reserved.