Mateusz Gebroski
Mateusz Gebroski

Reputation: 1334

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?

Upvotes: 4

Views: 824

Answers (1)

Eran
Eran

Reputation: 393781

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(" "));
}

Upvotes: 9

Related Questions