Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 filter but return all objects

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?

like image 318
Mateusz Gebroski Avatar asked Dec 31 '22 12:12

Mateusz Gebroski


1 Answers

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(" "));
}
like image 130
Eran Avatar answered Jan 03 '23 01:01

Eran