Sum of list with stream filter in Java
Last Updated :
15 May, 2021
We generally iterate through the list when adding integers in a range, but java.util.stream.Stream has a sum() method that when used with filter() gives the required result easily.
Java
import java.util.*;
class Addition {
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>();
list.add( 1 );
list.add( 5 );
list.add( 6 );
list.add( 7 );
list.add( 8 );
list.add( 9 );
list.add( 10 );
System.out.println(sum(list));
}
public static int sum(List<Integer> list)
{
Iterator<Integer> it = list.iterator();
int res = 0 ;
while (it.hasNext()) {
int num = it.next();
if (num > 5 ) {
res += num;
}
}
return res;
}
}
|
The above task can be easily performed using sum() method with filter() method
Java
import java.util.*;
class Addition {
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>();
list.add( 1 );
list.add( 5 );
list.add( 6 );
list.add( 7 );
list.add( 8 );
list.add( 9 );
list.add( 10 );
System.out.println(sum(list));
}
public static int sum(List<Integer> list)
{
return list.stream()
.filter(i -> i > 5 )
.mapToInt(i -> i)
.sum();
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...