Problem :
How do you calculate the sum of only unique elements from a list using Java 8 Streams?
✅ Example:
import java.util.Arrays;
import java.util.List;
public class SumOfUniqueNumbers {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(23, 45, 23, 15, 15, 78, 23, 85, 65);
// Calculate sum of unique numbers
int uniqueNumbersSum = numbers.stream()
.distinct() // Get only unique elements
.mapToInt(Integer::intValue) // Convert Integer to int
.sum(); // Sum the unique numbers
System.out.println("Sum of unique numbers: " + uniqueNumbersSum);
}
}
✅ Explanation:
- numbers.stream(): Creates a stream from the list of integers.
- distinct(): Removes duplicate elements from the stream, keeping only unique values.
- mapToInt(Integer::intValue): Converts
Integerobjects to primitiveintfor efficient processing. - sum(): Computes the sum of the resulting
IntStream. - Finally, the result is printed with
System.out.println().
✅ Output:
Sum of unique numbers: 311
Because the unique numbers are:
23 + 45 + 15 + 78 + 85 + 65 = 311