How to get a range of items from stream using Java 8 lambda?

To get a range from a Stream<T>, you can use skip(long n) to first skip a set number of elements, and then you can call limit(long n) to only take a specific amount of items.

Consider a stream with 10 elements, then to get elements 3 to 7, you would normally call from a List:

list.subList(3, 7);

Now with a Stream, you need to first skip 3 items, and then take 7 – 3 = 4 items, so it becomes:

stream.skip(3).limit(4);

As a variant to @StuartMarks’ solution to the second answer, I’ll offer you the following solution which leaves the possibility to chain intact, it works similar to how @StuartMarks does it:

private <T> Collector<T, ?, Stream<T>> topPercentFromRangeCollector(Comparator<T> comparator, double from, double to) {
    return Collectors.collectingAndThen(
        Collectors.toList(),
        list -> list.stream()
            .sorted(comparator)
            .skip((long)(list.size() * from))
            .limit((long)(list.size() * (to - from)))
    );
}

and

IntStream.range(0, 100)
        .boxed()
        .collect(topPercentFromRangeCollector(Comparator.comparingInt(i -> i), 0.1d, 0.3d))
        .forEach(System.out::println);

This will print the elements 10 through 29.

It works by using a Collector<T, ?, Stream<T>> that takes in your elements from the stream, transforms them into a List<T>, then obtains a Stream<T>, sorts it and applies the (correct) bounds to it.

Leave a Comment