Stream Limit

The Limit method defined in the Stream class is used to limit the result. Limit is an intermediate function, which returns a new Stream with a limited element count which was passed as a parameter.

package org.wesome.java8;

import java.util.Arrays;
import java.util.List;

class Apple {
    public static void main(String args[]) {
        final int LIMIT = 2;
        List<String> apples = Arrays.asList("Macintosh", "Fuji", "Gala", "Jonagold");
        System.out.println("*---------------------------Traditional method---------------------------*");
        for (int i = 0; i < LIMIT; i++) {
            System.out.println(apples.get(i));
        }

        System.out.println("*---------------------------Limit---------------------------*");
        apples.stream().limit(LIMIT).forEach(System.out::println);
    }
}

if the input count of the Stream is less than the limit provided, then the Limit will not throw any Exception but will return the available input.

package org.wesome.java8;

import java.util.Arrays;
import java.util.List;

class Apple {
    public static void main(String args[]) {
        int LIMIT = 5;
        List<String> apples = Arrays.asList("Macintosh", "Fuji", "Gala", "Jonagold");

        apples.stream().limit(LIMIT).forEach(System.out::println);
    }
}

a negative limit will throw an IllegalArgumentException.

package org.wesome.java8;

import java.util.Arrays;
import java.util.List;

class Apple {
    public static void main(String args[]) {
        int LIMIT = -5;
        List<String> apples = Arrays.asList("Macintosh", "Fuji", "Gala", "Jonagold");

        try {
            apples.stream().limit(LIMIT).forEach(System.out::println);
        } catch (IllegalArgumentException exception) {
            System.out.println(exception);
        }
    }
}

The limit function is majorly used to limit the output of the Infinite stream, it will not consume the entire Infinite stream but will stop execution as soon as the limit reaches, hence it's a short circuit operation.

package org.wesome.java8;

import java.util.Random;
import java.util.stream.Stream;

class Apple {
    public static void main(String args[]) {
        int limit = 2;
        /*-------------------------Infinite Stream using Math random-------------------------*/
        Stream.generate(Math::random).limit(limit).forEach(System.out::println);

        /*-------------------------Infinite Stream using Random-------------------------*/
        Stream.generate(Random::new).map(Random::nextInt).limit(limit).forEach(System.out::println);

        /*-------------------------Infinite Stream using Iterate-------------------------*/
        Stream.iterate(1, i -> i + 1).limit(limit).forEach(System.out::println);
    }
}

The Limit function is very expensive with parallel Stream gives a very poor performance as well because parallel threads will be computing streams and limiting them would require extra computation.

package org.wesome.java8;

import java.util.stream.IntStream;

class Apple {
    public static void main(String args[]) {
        System.out.println("*--------------Limit with Sequential Stream and forEach--------------*");
        long start = System.currentTimeMillis();
        IntStream.rangeClosed(1, 10).limit(5).forEach(System.out::println);
        long end = System.currentTimeMillis();
        long seqDuration = end - start;
        System.out.println("Limit with Sequential Stream and forEach took = " + seqDuration + " milliseconds");

        System.out.println("*--------------Limit with Parallel Stream and forEach--------------*");
        start = System.currentTimeMillis();
        IntStream.rangeClosed(1, 10).parallel().limit(5).forEach(System.out::println);
        end = System.currentTimeMillis();
        long parDuration = end - start;
        System.out.println("Limit with Parallel Stream and forEach = " + parDuration + " milliseconds");


        System.out.println("*--------------Limit with Sequential Stream and forEachOrdered--------------*");
        start = System.currentTimeMillis();
        IntStream.rangeClosed(1, 10).limit(5).forEachOrdered(System.out::println);
        end = System.currentTimeMillis();
        seqDuration = end - start;
        System.out.println("Limit with Sequential Stream and forEachOrdered took = " + seqDuration + " milliseconds");

        System.out.println("*--------------Limit with Parallel Stream and forEachOrdered--------------*");
        start = System.currentTimeMillis();
        IntStream.rangeClosed(1, 10).parallel().limit(5).forEachOrdered(System.out::println);
        end = System.currentTimeMillis();
        parDuration = end - start;
        System.out.println("Limit with Parallel Stream and forEachOrdered took = " + parDuration + " milliseconds");
    }
}

Stream class generate function with parallel processing result in very high throughput.

package org.wesome.java8;

import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

class Apple {
    public static void main(String args[]) {
        System.out.println("*--------------Stream Generate and forEach--------------*");
        LocalTime start = LocalTime.now();
        Stream.generate(Random::new).map(Random::nextInt).limit(5).forEach(System.out::println);
        LocalTime end = LocalTime.now();
        int duration = end.getNano() - start.getNano();
        System.out.println("Stream Generate and forEach took = " + TimeUnit.MILLISECONDS.convert(duration, TimeUnit.NANOSECONDS) + " milliseconds");

        System.out.println("*--------------Stream Generate and forEach--------------*");
        start = LocalTime.now();
        Stream.generate(Random::new).map(Random::nextInt).limit(5).forEachOrdered(System.out::println);
        end = LocalTime.now();
        duration = end.getNano() - start.getNano();
        System.out.println("Stream Generate and forEach took = " + TimeUnit.MILLISECONDS.convert(duration, TimeUnit.NANOSECONDS) + " milliseconds");
    }
}

follow us on