This post will demonstrate how to get sum of any particular field, for example, consider a List of Person class with property noOfMangoesEaten which represents how many mangoes an individual has consumed.
Using Java 8, we need to find how many mangoes in total have been consumed by all the persons inside a List.
We can use streams function to iterate the list and use mapToInteger function and gets sum out of it.
Here is an example
Person.java
package com.test; public class Person { private int noOfMangoesConsumed; public int getNoOfMangoesConsumed() { return noOfMangoesConsumed; } public void setNoOfMangoesConsumed(int noOfMangoesConsumed) { this.noOfMangoesConsumed = noOfMangoesConsumed; } }
SumOfFields.java -
package com.test; import java.util.ArrayList; import java.util.List; public class SumOfFields { public static void main(String args[]) { Person person = new Person(); person.setNoOfMangoesConsumed(100); Person person2 = new Person(); person2.setNoOfMangoesConsumed(200); List<Person> persons = new ArrayList<Person>(); persons.add(person); persons.add(person2); int sum = persons.stream().mapToInt(p -> p.getNoOfMangoesConsumed()).sum(); System.out.println("Total Mangoes Consumed - " + sum); } }
Output -
Total Mangoes Consumed - 300
No comments:
Post a Comment