Berisol
Berisol

Reputation: 77

How to use If statements in a stream?

I have to write a method that gets an Integer List and converts it into a String by adding "e" in front a number if it is even or "u" if it is uneven and then seperates them by ",". Example: Input:List with numbers 1,2,4,3-->Output:"u1,e2,e4,u3". The Problem is that I have to do it using lambda expressions and streams and I dont know how to differentiate between even and uneven numbers with them.

If I do it like this i can only do it for even or uneven Numbers:

public static String getString(List<Integer> list){
    String s = list.stream()
            .map(Object::toString)
            .filter(i->Integer.parseInt(i)%2==0)
            .map(i->"g"+i)
            .collect(Collectors.joining(","));
    return s;

}

How can i use something like an If statement in a stream to decide whether to put "e" or "u" in front of the number?

Upvotes: 6

Views: 4265

Answers (1)

Eran
Eran

Reputation: 393781

You can put the condition in the map operation. The easiest way is using the ternary condition operator.

BTW, there's no reason to convert the Integer to a String and then parse it again to an int.

public static String getString(List<Integer> list){
    return list.stream()
               .map(i->i%2==0?"e"+i:"u"+i)
               .collect(Collectors.joining(","));
}

EDIT: you can also use an if-else statement, but that would look less elegant:

public static String getString(List<Integer> list){
    return list.stream()
               .map(i -> {
                    if (i%2==0) {
                        return "e"+i;
                    } else {
                        return "u"+i;
                    }
                })
               .collect(Collectors.joining(","));
}

Upvotes: 7

Related Questions