Java 8 : Multiple conditions in map function of stream

Junaid :

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.

Ravindra Ranwala :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=89495&siteId=1