【发布时间】:2014-11-24 13:17:20
【问题描述】:
我想知道是否可以使用新的 Streams API 在一行中执行以下操作:
List<MyItem> arr = new ArrayList<>();
// MyItem has a single field, which is a value
arr.add(new MyItem(3));
arr.add(new MyItem(5));
// the following operation is the one I want to do without iterating over the array
int sum = 0;
for(MyItem item : arr){
sum += item.getValue();
}
如果数组只包含ints,我可以这样做:
int sum = array.stream().mapToInt(Integer::intValue).sum();
但是,我可以将相同的想法应用于任意对象列表吗?
【问题讨论】:
标签: java collections java-8