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?
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) .
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(","));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With