简体   繁体   中英

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.

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

Another way to do that using List.replaceAll could be:

List<String> cs = Arrays.asList("agent", "manager", "admin");
cs.replaceAll(s -> {
    if (s.equals("manager")) {
        return "agent";
    }
    if (s.equals("agent")) {
        return "manager";
    }
    return s;
});

The other answers show how to deal with 2 options to replace elements. Here's a more general approach:

Map<String, String> replacements = Map.of("agent", "manager", "manager", "agent");

List<String> replace = cs.stream()
    .map(p -> replacements.getOrDefault(p, p))
    .collect(Collectors.toList());

If you have more words to be replaced, simply add them to the replacements map.

For readability you can check this

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

List<String> replace = cs.stream()
.map(p -> { 
  if(p.equals("agent"))
   p = "manager"; 
  else if(p.equals("manager"))
   p = "agent; 

  return p;
})
.collect(Collectors.toList());

Another way would be like this:

cs.replaceAll(s->s.replaceAll("agent|manager",replace(s)));



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

This will help you in this case but if you need more conditions use body style smth like this

map(p -> {...})

for creating readable code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM