[FIXED] Java Stream usage

Issue

I have a usecase 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]

Solution

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

Answered By – Chaosfire

Answer Checked By – Senaida (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published