In this short tutorial, we will see how to map and filter a list with Java lambdas.
1) Map a list
Let’s start from a list of integers:
List<Integer> list = List.of(1, 3, 6, 2, 4, 5);
To map the list, we need to convert it into a stream, then map it and finally collect it:
list = list.stream().map(i -> 2 * i).collect(Collectors.toList());
Here each element is multiplied by 2.
2) Filter a list
To filter a list, we need to convert it into a stream, then filter it and finally collect it:
list = list.stream().filter(i -> i < 10).collect(Collectors.toList());
Here we only keep elements smaller than 10.
3) Full code demo
If you run the code above, you will get this result in the console:
Original: [1, 3, 6, 2, 4, 5] Mapped: [2, 6, 12, 4, 8, 10] Filtered: [2, 6, 4, 8]
which is the expected result.
That’s it for this tutorial ! If you have any question, please leave a reply below, we answer within 24 hours.