Java Stream How to - Limit result to two








Question

We would like to know how to limit result to two.

Answer

import static java.util.stream.Collectors.toList;
/* w w w.  jav  a  2 s  .c  o  m*/
import java.util.Arrays;
import java.util.List;

public class Main {

  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
    List<Integer> twoEvenSquares = 
          numbers.stream()
                 .filter(n -> n % 2 == 0)
                 .map(n -> n * n)
                 .limit(2)
                 .collect(toList());

    System.out.println(twoEvenSquares);
  }

}

The code above generates the following result.