I need to find words which are greater than 5 chars and then reverse it. Such code works fine:
public class SpinWords {
    private Function<String, String> reverse = s -> new StringBuilder(s).reverse().toString();
    public String spinWords(String sentence) {
        String whitespace = " ";
        List<String> split = Arrays.asList(sentence.split(whitespace));
        return split.stream().map(s -> {
            if (s.length() > 5) {
                s = reverse.apply(s);
            }
            return s;
        }).collect(Collectors.joining(whitespace));
    }
}
but since I am learning java 8 now I would like to replace this is statement into stream without braces but using java 8 alternatives. Is it possible or this code is valid?
You can use the ternary conditional operator:
return split.stream()
            .map(s -> s.length() > 5 ? reverse.apply(s) : s)
            .collect(Collectors.joining(whitespace));
EDIT: As Naman suggested, the entire method can be reduced to a single statement:
public String spinWords(String sentence) {
    return Arrays.stream(sentence.split(" "))
                 .map(s -> s.length() > 5 ? reverse.apply(s) : s)
                 .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