ArrayList将所有对象更改为一个属性值

时间:2015-01-27 19:28:08

标签: java list collections

Java Spring Collection

List<CustomObject> myList = new ArrayList<CustomObject>(1000); // list with thousnda objects

我想设置列表中所有对象的CustomObject属性“type”。简单的方法是运行循环并设置如下属性。

for(CustomObject obj:myList){
obj.setType('value'); 
}

我想让代码看起来更好一点,所以如果有任何其他方式在一行代码中做同样的事情?

2 个答案:

答案 0 :(得分:6)

在Java 8中:

myList.forEach(c -> c.setType("value"));

答案 1 :(得分:1)

您可以使用Guava Collections

List<CustomObject> initializedList = Lists.transform(myList, new Function<CustomObject, CustomObject>() {
    @Override
    public CustomObject apply(CustomObject obj) {
        return obj.setType("value");
    }
});