LongStream example

In Java 8, java.util.stream.LongStream was introduced to deal with primitive longs which brings a new way to solving old problems of finding max or largest value in array, find min or smallest value in array, sum all elements in array, and average of all values in array. These numeric reductions of max, min, sum and average make what used to be a hard tedious challenge much simpler. If you are looking to apply these techniques the stream reduction example or LongSummaryStatistics, a specialized object for collecting statistics, show how to use them.

In these examples we will show common methods exposed by LongStream that deal with long-value elements. In addition to dealing with ints, DoubleStreams is a specialized class to deal with primitive double and IntStream for dealing with primitive type int.

builder

There are various ways to build a stream and LongStream has a builder that allows you to chain together calls to set up configuration followed by a build method that creates the stream. This code snippet below makes a call to the builder and then adds two primitive int values. It then calls the sum method to find the sum of the stream.

@Test
public void longstream_builder() {

    long sum = LongStream.builder().add(10).add(10).build().sum();

    assertEquals(20, sum, 0);
}

concat

In the event where you have seperate streams, DoubleStream provides the ability to concat or combine streams together. To demonstrate this we created two streams via the builder, concatenated and then called the sum method.

@Test
public void longstream_concat() {

    LongStream first = LongStream.builder().add(10).build();
    LongStream second = LongStream.builder().add(10).build();

    LongStream third = LongStream.concat(first, second);

    assertEquals(20, third.sum(), 0);
}

empty

The LongStream.empty returns an empty sequential LongStream.

@Test
public void longstream_empty() {

    LongStream emptyStream = LongStream.empty();

    assertEquals(0, emptyStream.count());
}

generate

The LongStream.generate allows you to produce an infinite stream of values on demand. In the code snippet below we will generate 10 longs and then find the distinct elements which will return numeric 1.

@Test
public void longstream_generate() {

    OptionalLong one = LongStream.generate(() -> 1).limit(10)
            .distinct().findFirst();

    assertEquals(1, one.getAsLong(), 0);
}

iterate

Similar to the LongStream.generate, the LongStream.iterate will return an infinite sequential ordered LongStream. The first parameter to LongStream.iterate is the seed and in our case 0. It will iterate from 0 and for every element will add 3, so 0 + 3, 3 + 3 and so on. Since we apply the limit it will return 3 iterations thus returning 0, 3, 6.

@Test
public void longstream_iterate() {

    List<Long> numbers = LongStream.iterate(0, n -> n + 3).limit(3)
            .boxed().collect(Collectors.toList());

    assertThat(numbers,
            contains(new Long(0), new Long(3), new Long(6)));
}

of

The LongStream.of method returns a stream whose elements are specified. Below a stream will be initialized with 5,10 and then max taken which will return 10 as the unit test reads.

@Test
public void longstream_of() {

    OptionalLong max = LongStream.of(5, 10).max();

    assertEquals(10, max.getAsLong(), 0);
}

Map to LongStream

This example will take an ArrayList of strings and then map them to an LongStream by passing Integer.parseInt. Then for testing purposes we will call LongStream.max which will return 3.

@Test
public void map_to_longstream() {

    List<String> longs = new ArrayList<String>();
    longs.add("1");
    longs.add("2");
    longs.add("3");

    OptionalLong longStream = longs.stream()
            .mapToLong(Long::parseLong).max();

    assertEquals(3, longStream.getAsLong(), 0);
}

Convert to stream of objects

If you are looking to convert LongStream to a stream of Longs, you can call boxed method which returns the elements in the stream each boxed to an Long.

@Test
public void convert_to_stream_of_objects() {

    long[] numbers = { 1, 2, 3, 4, 5, 6 };

    List<Long> listOfLongs = Arrays.stream(numbers).boxed()
            .collect(Collectors.toList());

    assertThat(
            listOfLongs,
            contains(new Long(1), new Long(2), new Long(3),
                    new Long(4), new Long(5), new Long(6)));

}

Specify default

OptionalLong is a specialized version of Optional. In the instance where you want to provide a default other than 0, you can call the OptionalLong.orElse. In this example, we want to find the max value of an empty list. Since there isn't any values present it will return 5.

@Test
public void provide_default() {

    List<String> longs = new ArrayList<String>();

    long optionalLong = longs.stream()
            .mapToLong(Long::parseLong).max().orElse(5);

    assertEquals(5, optionalLong, 0);
}