Learn Java 8 streams with an example - Summing Numbers

Example 1: Using Stream.collect()

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class DriverClass {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(2, 9, 10, 8, 4, 7);
Integer sum = integers.stream()
.collect(Collectors.summingInt(Integer::intValue));
System.out.println("Sum= " + sum);
}
}
Similarly, the Collectors class provides summingDouble() and summingLong()

Example 2: Using Stream.reduce()

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class DriverClass {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(2, 9, 10, 8, 4, 7);
Integer sum = integers.stream()
.reduce(0, (a, b) -> a + b);
System.out.println("Sum="+sum);
}
}

Example 3: Using IntStream.sum()

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class DriverClass {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(2, 9, 10, 8, 4, 7);
Integer sum = integers.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum= " + sum);
}
}

Example 4: Sum of all numbers in an array

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class DriverClass {
public static void main(String[] args) {
int[]integers = {2, 9, 10, 8, 4, 7};
int sum = Arrays.stream(integers).sum();
System.out.println("Sum= " + sum);
}
}

Example 5: Sum of all numbers in a Set

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class DriverClass {
public static void main(String[] args) {
Set<Integer> integers = Stream.of(2, 9, 10, 8, 4, 7).
                        collect(Collectors.toSet());
Integer sum = integers.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum= " + sum);
}
}


More...

Comments