Looking to get a head start on your next software interview? Pickup a copy of the best book to prepare: Cracking The Coding Interview!
Here’s an example of how to use the map() method in Java:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> squaredNumbers = numbers.stream()
.map(n -> n * n)
System.out.println(squaredNumbers); // Output: [1, 4, 9, 16, 25]
In this example, we first create a list of integers using the Arrays.asList() method. We then create a new stream from this list using the stream() method. We use the map() method to transform each element of the stream by squaring it. Finally, we collect the transformed elements into a new list using the collect() method.
The output of this code will be a list of integers where each element is the square of the corresponding element in the original list.