Java初始化对象和使用Stream的set属性

时间:2018-11-12 10:08:42

标签: java dictionary java-stream

我正在尝试将列表克隆到新列表并在新列表中设置属性。 我正在尝试使用Java8 Stream,因为它使克隆变得简单。 我的代码可以正常工作,但是它使Sonar产生了这种代码味道:

  

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

有没有一种方法可以不使用局部变量? 代码:

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

谢谢

3 个答案:

答案 0 :(得分:1)

这是一个警告,因为您不必要地使用了新变量cloned,而不是像这样直接链接函数

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

答案 1 :(得分: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());

答案 2 :(得分:0)

您可以尝试以下方法:

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