squaring first three even numbers using java 8?

Here we find the squaring first three even numbers using java 8.

  • First convert Arrays to list using Arrays.asList() method.
  • Now get the Stream data from List using arrayList.stream() method.
  • From filter, we only find the even number using filter(a -> a % 2 == 0) method.
  • In Map each number to its square using map(b->b*b).
  • Now limit the stream of first three even numbers.
  • From collect() method, we collect all the square numbers in list.
  • Print the squaring of first three even numbers.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SquareTest {
	public static void main(String[] args) {
		List<Integer> num = Arrays.asList(4, 23, 20, 45, 30, 123, 100);

		List<Integer> listNumber = num.stream().filter(a -> a % 2 == 0).map(b -> b * b).limit(3).collect(Collectors.toList());
		System.out.println("squares of the first three even numbers are :- " + listNumber);
	}
}

Output :-
squares of the first three even numbers are :- [16, 400, 900]