- Сумма всех элементов Java Arraylist
- 4 ответа
- Sum all elements in ArrayList Java 8
- 2. Sum all the elements in the ArrayList using Java 8
- 3. Alternative ways to sum all elements in the ArrayList
- 4. Conclusion
- Java 8 Sum: Array, Map and List Collection Example using reduce() and collect() Method
- Sum using IntStream.sum()
- Sum using Collectors.summingInt() with Stream.collect()
- Sum using Collectors.summarizingInt() with Stream.collect() and IntSummaryStatistics
- Sum using Stream.reduce() with BiFunction and BinaryOperator
- Sum using Stream.reduce() with Custom Method
- Sum of Array Example
- Sum of List Example
- Sum of List of Array Example
- Sum of Map Example
- Sum in Java 8 – array, list and map using reduce method
- Example
- Other Useful References:
- Author
- Related posts:
- Submit a Comment Cancel reply
- Subscribe to our Newsletter
- About Techndeck
- Privacy Overview
- How to find sum of array elements in java
Сумма всех элементов Java Arraylist
Подсказка: чтобы получить значение из списка в указанной позиции, вы можете использовать m.get(indexOfPosition) .
или Используйте: JAVA 8 для версий int, int sum = list.stream (). mapToInt (Integer :: intValue) .sum ();
Этот вопрос должен быть вновь открыт. Это действительно, определенно и полезно. Посмотрите на положительные голоса на вопросы и ответы. Посмотрите на более новую информацию, добавляемую об использовании Java Streams для функционального решения.
4 ответа
double sum = 0; for(int i = 0; i < m.size(); i++) sum += m.get(i); return sum;
Используйте стиль "для каждого":
double sum = 0; for(Double d : m) sum += d; return sum;
Почему ты так думаешь ?? Это вызывает снижение производительности ?? Меньше и Чистый Кодекс, на который я надеялся!
@AnandVarkeyPhilips The 😛 в конце комментария Барранки означает, что она / он шутил или наполовину шутил. См. Список смайликов : язык торчит, дерзкий / игривый, дует малина .
@AnandVarkeyPhilips Я не хотел вас обидеть, и я думаю, что ваше решение неверно. Ваш ответ правильный, и я просто пошутил (спасибо BasilBourque для указания его)
лол . я изучал потоки и думал, что это будет полезно для кого-то, читающего это здесь . тогда твой комментарий заставил меня подумать, что это приведет к некоторому снижению производительности .. я не знаю .. вот почему я спросил . 🙂
Sum all elements in ArrayList Java 8
In this article, we will learn to sum all the elements in the ArrayList using Java 8. To learn more about Java streams, refer to these articles.
2. Sum all the elements in the ArrayList using Java 8
A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum of a set of numbers. The streams classes have multiple specialized reduction forms such as sum() , max() , or count() .
So, we can use this sum() reduction operation to get the sum of all the elements in the ArrayList .
The sum operation returns the sum of elements in this stream. This is a special case of a reduction and is equivalent to:
return reduce(0, Integer::sum);
This is a terminal operation. The Terminal operations may traverse the stream to produce a result. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
List ints = Arrays.asList(1, 2, 3, 4, 5); List longs = Arrays.asList(1L, 2L, 3L, 4L, 5L); List doubles = Arrays.asList(1.2d, 2.3d, 3.0d, 4.0d, 5.0d); List floats = Arrays.asList(1.3f, 2.2f, 3.0f, 4.0f, 5.0f); long intSum = ints.stream() .mapToLong(Integer::longValue) .sum(); long longSum = longs.stream() .mapToLong(Long::longValue) .sum(); double doublesSum = doubles.stream() .mapToDouble(Double::doubleValue) .sum(); double floatsSum = floats.stream() .mapToDouble(Float::doubleValue) .sum(); System.out.println(String.format( "Integers: %s, Longs: %s, Doubles: %s, Floats: %s", intSum, longSum, doublesSum, floatsSum));
3. Alternative ways to sum all elements in the ArrayList
3.1. We can implement using the simple sequential loops, as in:
int sum = 0; for (int x : numbers)
3.2. We can use the general-purpose reduce operation directly. These reduction operations can run safely in parallel with almost no modification:
int sum = numbers.stream().reduce(0, (x,y) -> x+y); or int sum = numbers.stream().reduce(0, Integer::sum); int sum = numbers.parallelStream().reduce(0, Integer::sum);
Parallel streams enable us to execute code in parallel on separate cores. The final result is the combination of each individual outcome. However, the order of execution is out of our control. It may change every time we run the program:
4. Conclusion
To sum up, we have learned to sum all the elements in the list using Java 8. To learn more about Java streams, refer to these articles.
Java 8 Sum: Array, Map and List Collection Example using reduce() and collect() Method
On this page we will provide Java 8 sum of values of Array, Map and List collection example using reduce() and collect() method. There are various ways to calculate the sum of values in java 8. We can use IntStream.sum() . We can get sum from summary statistics. We can also create our own method to get the sum. We will discuss here different ways to calculate the sum.
Contents
Sum using IntStream.sum()
int sum = map.values().stream().mapToInt(i->i).sum(); int sum = list.stream().map(Line::getLength).mapToInt(Integer::intValue).sum();
Sum using Collectors.summingInt() with Stream.collect()
To get the sum of values we can use Collectors.summingInt() with Stream.collect() for integer data type.
int sum = list.stream().map(Line::getLength).collect(Collectors.summingInt(i->i));
Sum using Collectors.summarizingInt() with Stream.collect() and IntSummaryStatistics
To get the sum of values we can use Collectors.summarizingInt() with Stream.collect() and IntSummaryStatistics .
IntSummaryStatistics stats = list.stream() .collect(Collectors.summarizingInt(Line::getLength)); IntSummaryStatistics stats = list.stream().flatMap(a->Arrays.stream(a)) .collect(Collectors.summarizingInt(i->i)); System.out.println(stats.getSum());
For long data type, we use summingLong with LongSummaryStatistics and for double data type there is summingDouble with DoubleSummaryStatistics in java 8.
Here Line is our custom class.
Line.java
package com.concretepage; public class Line < private int length; public Line(int length) < this.length = length; >public int getLength() < return length; >>
Sum using Stream.reduce() with BiFunction and BinaryOperator
To get the sum of values we can use Stream.reduce() with BiFunction as accumulator and BinaryOperator as combiner in parallel processing.
int sum = list.parallelStream().reduce(0, (output, ob) -> output + ob.getLength(), (a, b) -> a + b);
Here 0 is an identity. Identity is operated using BinaryOperator to each and every element of stream. If identity is 0, then it results into the sum of elements of stream in our example.
Sum using Stream.reduce() with Custom Method
int sum = Arrays.stream(array).reduce(0, StatisticsUtility::addIntData);
package com.concretepage; public class StatisticsUtility < public static int addIntData(int num1, int num2) < return num1 + num2; >>
int sum = Arrays.stream(array).reduce(0, Integer::sum);
Sum of Array Example
package com.concretepage; import java.util.Arrays; import java.util.function.IntBinaryOperator; public class SumOfArrayDemo < public static void main(String[] args) < int[] array = ; System.out.println("--Using IntStream.sum()--"); int sum = Arrays.stream(array).sum(); System.out.println(sum); System.out.println("--Using Stream.reduce() with IntBinaryOperator--"); IntBinaryOperator ibop = (x,y) -> x+y; sum = Arrays.stream(array).reduce(0, ibop); System.out.println(sum); System.out.println("--Using Stream.reduce() with Integer.sum()--"); sum = Arrays.stream(array).reduce(0, Integer::sum); System.out.println(sum); System.out.println("--Using custom method--"); sum = Arrays.stream(array).reduce(0, StatisticsUtility::addIntData); System.out.println(sum); > >
--Using IntStream.sum()-- 251 --Using Stream.reduce() with IntBinaryOperator-- 251 --Using Stream.reduce() with Integer.sum()-- 251 --Using custom method-- 251
Sum of List Example
package com.concretepage; import java.util.ArrayList; import java.util.IntSummaryStatistics; import java.util.List; import java.util.stream.Collectors; public class SumOfListDemo < public static void main(String[] args) < List<Line> list = new ArrayList<>(); list.add(new Line(213)); list.add(new Line(233)); list.add(new Line(243)); list.add(new Line(253)); System.out.println("--Using IntStream.sum()--"); int sum = list.stream().map(Line::getLength).mapToInt(Integer::intValue).sum(); System.out.println(sum); System.out.println("--Using Collectors.summingInt()--"); sum = list.stream().map(Line::getLength).collect(Collectors.summingInt(i->i)); System.out.println(sum); System.out.println("--Using summarizingInt()--"); IntSummaryStatistics stats = list.stream() .collect(Collectors.summarizingInt(Line::getLength)); System.out.println(stats.getSum()); System.out.println("--Using Stream.reduce() with combiner--"); sum = list.parallelStream().reduce(0, (output, ob) -> output + ob.getLength(), (a, b) -> a + b); System.out.println(sum); >>
--Using IntStream.sum()-- 942 --Using Collectors.summingInt()-- 942 --Using summarizingInt()-- 942 --Using Stream.reduce() with combiner-- 942
Sum of List of Array Example
package com.concretepage; import java.util.ArrayList; import java.util.Arrays; import java.util.IntSummaryStatistics; import java.util.List; import java.util.stream.Collectors; public class SumOfListOfArrayDemo < public static void main(String[] args) < List<Integer[]> list = new ArrayList<>(); Integer[] a1 = ; list.add(a1); Integer[] a2 = ; list.add(a2); System.out.println("--Using Collectors.summingInt()--"); int sum = list.stream().flatMap(a->Arrays.stream(a)). collect(Collectors.summingInt(i->i)); System.out.println(sum); System.out.println("--Using Collectors.summarizingInt()--"); IntSummaryStatistics stats = list.stream().flatMap(a->Arrays.stream(a)) .collect(Collectors.summarizingInt(i->i)); System.out.println(stats.getSum()); System.out.println("--Using IntStream.sum()--"); sum = list.stream().flatMap(a->Arrays.stream(a)). mapToInt(Integer::intValue).sum(); System.out.println(sum); > >
--Using Collectors.summingInt()-- 81 --Using Collectors.summarizingInt()-- 81 --Using IntStream.sum()-- 81
Sum of Map Example
package com.concretepage; import java.util.HashMap; import java.util.IntSummaryStatistics; import java.util.Map; import java.util.stream.Collectors; public class SumOfMapValues < public static void main(String[] args) < Map<Integer, Integer> map = new HashMap<>(); map.put(1, 12); map.put(2, 24); map.put(3, 10); System.out.println("--Using IntStream.sum()--"); int sum = map.values().stream().mapToInt(i->i).sum(); System.out.println(sum); System.out.println("--Using BinaryOperator--"); sum = map.values().stream().reduce(0, Integer::sum); System.out.println(sum); System.out.println("--Using Collectors.summingInt()--"); sum = map.values().stream().collect(Collectors.summingInt(i->i)); System.out.println(sum); System.out.println("--Using Collectors.summarizingInt()--"); IntSummaryStatistics stats = map.values().stream().collect(Collectors.summarizingInt(i->i)); System.out.println(stats.getSum()); System.out.println("--Using custom method--"); sum = map.values().stream().reduce(0, StatisticsUtility::addIntData); System.out.println(sum); >>
--Using IntStream.sum()-- 46 --Using BinaryOperator-- 46 --Using Collectors.summingInt()-- 46 --Using Collectors.summarizingInt()-- 46 --Using custom method-- 46
Sum in Java 8 – array, list and map using reduce method
In this tutorial, we will see “How to perform sum operation on arrays, list and map objects using reduce method in Java 8” .
Example
Do you like this Post? – then check my other helpful posts:
Other Useful References:
Author
Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks. View all posts
Related posts:
Submit a Comment Cancel reply
Subscribe to our Newsletter
About Techndeck
Techndeck.com is a blog revolves around software development & testing technologies. All published posts are simple to understand and provided with relevant & easy to implement examples.
Techndeck.com’s author is Deepak Verma aka DV who is an Automation Architect by profession, lives in Ontario (Canada) with his beautiful wife (Isha) and adorable dog (Fifi). He is crazy about technologies, fitness and traveling etc. He runs a Travel Youtube Channel as well. He created & maintains Techndeck.com
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
How to find sum of array elements in java
Sum of array elements means the sum of all the elements(or digits) in the array. Array elements can be integers( int ) or decimal numbers( float or double ).
There are different methods to calculate sum of elements in an array in java and this post discusses them all.
Method 1 : Using for loop
This is a traditional and most commonly used approach where the array is iterated using a for loop.
In each iteration, the current array element is added to a variable which holds the sum of array elements.
This variable is initialized to 0 before the start of loop. Example,
public class ArraySumCalculator { public static void main(String[] args) { int[] array = { 1, 34, 67, 23, -2, 18 }; // variable to hold sum of array elements int sum = 0; // iterate using a for loop for (int loopCounter = 0; loopCounter < array.length; loopCounter++) { // get current array element int element = array[loopCounter]; // add element to sum sum += element; } System.out.println("Sum of array elements is: " + sum); } }
public class ArraySumCalculator < public static void main(String[] args) < int[] array = < 1, 34, 67, 23, -2, 18 >; // variable to hold sum of array elements int sum = 0; // iterate using a for loop for (int loopCounter = 0; loopCounter < array.length; loopCounter++) < // get current array element int element = array[loopCounter]; // add element to sum sum += element; >System.out.println("Sum of array elements is: " + sum); > >
Sum of array elements is: 141
for loop in this program can also be replaced with a for-each loop as shown below.