I want to use a stream to sum List
long sum = list.stream().mapToLong(User::getAge).sum();
But the numbers stored in my list are basic types, which is not applicable. Later, I found the answer in the IBM developer community:
long sum = list.stream().reduce(Integer::sum).orElse(0);
It seems that I am still not familiar with the convection operation.
List<Integer> list = new ArrayList<Integer>()
List
List is an interface
Indicates what type of object is placed in the List. Writing it like this means that the object placed in your List must be of type Integer
#int is one of the 8 primitive data types provided by java.
Java provides a wrapper class for each primitive type. Integer is a wrapper class provided by java for int. The default value of int is 0, while the default value of Integer is null
Integer provides multiple integer-related operation methods, for example, convert a string into an integer, in Integer Constants representing the maximum and minimum values of integers are also defined.
The ArrayList class is a special array - a dynamic array. By adding and removing elements, you can dynamically change the length of the array.
Advantages:
#1. Supports automatic size change
2. Can be flexibly inserted Element
3. You can flexibly delete elements
Limitations:
Than ordinary arrays The speed is slower;
ArrayList is an implementation class of the List interface.
The ArrayList class is an implementation class that inherits the AbstractList abstract class and implements the List interface.
Therefore, the List interface cannot be constructed, that is to say, we cannot create instance objects, but we can create an object reference pointing to ourselves for the List interface as follows, and the instance object of the ArrayList implementation class is This acts as an object reference to the List interface.
List interface;
The above is the detailed content of How to implement the sum of List<Integer> in Java8. For more information, please follow other related articles on the PHP Chinese website!