1

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]
1
  • The filter filters out 1 because 1 % 2 == 1 Commented Sep 9, 2022 at 14:28

3 Answers 3

8

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());
Sign up to request clarification or add additional context in comments.

Comments

1

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);

2 Comments

This would be fine as a comment to the OP, but it is very clear that a stream based solution is wanted, so this is not answering the question that was asked; it is just needless noise.
I disagree with the above comment that this should not have been posted as an answer. It solves the actual problem being presented, and it is not clear from the question that the use of streams is actually a hard requirement.
0

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());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.