How to use a single conditional statement while streaming a Set<String>

Viewed 49

I have a Set<String> allNames. I am creating a new Set by applying some filtering.

Set<String> allNames = Set.of(
    "Alex",
    "Joseph",
    "Mark",
    "John",
    "Peter",
    "Joe",
    "Adam",
    "Harry",
    "Jacob",
    "Alan"
);
Set<String> filteredSet = allNames.stream()
    .filter(name -> names.startsWith("Jo")
    .collect(toSet());

I have another Set<String> thirdPartySet coming from some API call. I want to check if this thirdPartySet is null then filtered out the names which are starting from Al otherwise keep them.

I tried to use filter(x -> thirdPartySet == null ? !x.startsWith("Al")) but since it's a ternary operator it is asking an else conditon. Is there any way I can achieve if condition while streaming?

1 Answers

If thirdPartySet is null, check if x doesn't start with "Al":

filter(x -> thirdPartySet != null || !x.startsWith("Al"))

You asked about an if:

filter(x -> {
    if (thirdPartySet == null) {
        return !x.startsWith("Al");
    }
    return true;
})
Related