Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 514
Berisol Avatar asked May 10 '18 11:05

Berisol


People also ask

How do I add an IF condition in stream API?

The ' if' Condition with PredicatesArrayList<Integer> numberList = new ArrayList<>(Arrays. asList(1,2,3,4,5,6)); Predicate<Integer> isEven = i -> i % 2 == 0; numberList. stream() . filter(isEven) .


1 Answers

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(","));
}
like image 75
Eran Avatar answered Sep 20 '22 01:09

Eran