Home  >  Article  >  Java  >  How to implement the sum of List<Integer> in Java8

How to implement the sum of List<Integer> in Java8

PHPz
PHPzforward
2023-05-14 22:34:042042browse

Summation of List in Java8

I want to use a stream to sum List, but after searching for the data, I always search for a field in the Object in List The sum is like this:

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.

Explanation List<Integer> list = new ArrayList<Integer>()

List list = new ArrayList()

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

About integer

How to implement the sum of List<Integer> in Java8

  • #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.

About ArrayList

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.

The purpose of this code is to call the built-in functions, add, get and other methods in the

List interface;

How to implement the sum of List<Integer> in Java8

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete