Sum unique values of numeric streams

This example will demonstrate how sum unique values from two IntStreams. In the snippet below we will first concatenate two streams by calling the IntStream.concat. This will give us a stream that contains values of both streams. To find the distinct set of elements we will call the Stream.distinct. Next, we want to peform a sum reduction operation that will give us the sum of unique values from two streams or 6 (3 + 2 + 1).

Note: This same behavior could be executed with either a DoubleStream or LongStream.


public void sum_unique_values_intstream() {

    IntStream stream1 = IntStream.of(1, 2, 3);
    IntStream stream2 = IntStream.of(1, 2, 3);

    int val = IntStream.concat(stream1, stream2).distinct().sum();

    assertEquals(6, val);

    // or
    IntStream stream3 = IntStream.of(1, 2, 3);
    IntStream stream4 = IntStream.of(1, 2, 3);

    OptionalInt sum2 = IntStream.concat(stream3, stream4).distinct()
            .reduce((a, b) -> a + b);

    assertEquals(6, sum2.getAsInt());