我想知道是否可以使用新的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();
}
如果数组只包含int
,我可以做这样的事情:
int sum = array.stream().mapToInt(Integer::intValue).sum();
但是,我可以将相同的想法应用于任意对象列表吗?
答案 0 :(得分:6)
你仍然可以做到。只需更改映射方法:
int sum = arr.stream().mapToInt(MyItem::getValue).sum();
您甚至可以将整个代码段缩减为一行:
int sum = Stream.<MyItem>Of(new MyItem(3),new MyItem(5)).mapToInt(MyItem::getValue).sum();
甚至更短(感谢@ MarkoTopolnik的评论):
int sum = Stream.Of(new MyItem(3),new MyItem(5)).mapToInt(MyItem::getValue).sum();