我正在尝试将列表克隆到新列表并在新列表中设置属性。 我正在尝试使用 Java8 Stream,因为它使克隆变得简单。 我的代码可以工作,但它从声纳中发出了代码味道:
局部变量不应声明后立即返回或抛出(squid:S1488)
有没有办法在不使用局部变量的情况下做到这一点? 代码:
List<myObject> clonedList = listToClone.stream()
.map(item -> {
cloned = new myObject(item);
cloned.setLifeCycle("someLifeCycle");
return cloned;
})
.collect(Collectors.toList());
谢谢
这是一个警告,因为您不必要地使用了新变量
cloned
,而不是像这样直接链接函数
List<myObject> clonedList = listToClone.stream()
.map(item -> {return (new myObject(item)).setLifeCycle("someLifeCycle");})
.collect(Collectors.toList());
你可以试试这个:
List<myObject> clonedList = listToClone.stream()
.map(myObject::new)
.map(o -> {
o.setLifeCycle("someLifeCycle");
return o;
})
.collect(Collectors.toList());
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());
这可以使用 Java Stream 的 .peek() 来完成
List<myObject> clonedList =
listToClone.stream()
.map(myObject::new)
.peek(x -> x.setLifeCycle("someLifeCycle"))
.collect(Collectors.toList());