Junaid
Junaid

Reputation: 674

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.

Upvotes: 4

Views: 15753

Answers (6)

fps
fps

Reputation: 34460

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.

Upvotes: 2

Garik Kalashyan
Garik Kalashyan

Reputation: 139

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.

Upvotes: 1

Hadi
Hadi

Reputation: 17289

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

Upvotes: 0

HuntsMan
HuntsMan

Reputation: 792

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

Upvotes: 0

Naman
Naman

Reputation: 31878

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

Upvotes: 2

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

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

Upvotes: 5

Related Questions