Reputation: 79
I have a use case where I want to modify some entries in a list based on some condition and leave the rest as it is. For this I am thinking of using Java streams but I could not find a solution that will work. I know using filter
and map
won't work as it will filter out the elements which do not satisfy the condition. Is there something that I can use?
Example:
List<Integer> a = new ArrayList<>();
a.add(1); a.add(2);
// I want to get square of element if element is even
// Current solution
List<Integer> b = a.stream().filter(i -> i % 2 == 0).map(i -> i * i).collect(Collectors.toList());
// This outputs - b = [4]
// But I want - b = [1, 4]
Upvotes: 1
Views: 319
Reputation: 16508
You don't realy need streams and create a new list if all you want is modify some entries. Instead you can use List#replaceAll
a.replaceAll(i -> i % 2 == 0 ? i * i : i);
Upvotes: 1
Reputation: 555
You can just put the condition in the map like this:
List<Integer> a = new ArrayList<>();
a.add(1);
a.add(2);
List<Integer> b = a.stream().map(i -> i % 2 == 0 ? i * i : i).collect(Collectors.toList());
Upvotes: 0
Reputation: 7005
You can make the map operation conditional and remove the filter:
List<Integer> b = a.stream()
.map(i -> i % 2 == 0 ? i * i : i)
.collect(Collectors.toList());
Upvotes: 8