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