Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 : Multiple conditions in map function of stream

How to use multiple condtions in map function of stream ? I'm new to Java streams actually I want to use multiple condtions in a stream map something like:

List<String> cs = Arrays.asList("agent", "manager", "admin");

List<String> replace = cs.stream()
.map(p -> p.equals("agent") ? "manager" : p || p.equals("manager") ? "agent" : p )
.collect(Collectors.toList());

What I want is to replace agent with manager and manager with agent. That's if in a list agent exist replace it with manager and if manager exist replace it with agent.

like image 279
Junaid Avatar asked Jan 27 '23 05:01

Junaid


1 Answers

You may do it like so,

List<String> interchanged = cs.stream()
    .map(s -> s.equals("manager") ? "agent" : s.equals("agent") ? "manager" : s)
    .collect(Collectors.toList());
like image 192
Ravindra Ranwala Avatar answered Jan 31 '23 09:01

Ravindra Ranwala