tli
tli

Reputation: 33

More elegant way to implement

ArrayList<Boolean> values = new ArrayList<>(Arrays.asList(true, false, true, false, false, true));

List<String> filter = Arrays.asList("TRUE");
List<String> filter = Arrays.asList("FALSE");
List<String> filter = Arrays.asList("TRUE","FALSE");

if (!filter.isEmpty()) {
    List<Boolean> collect = values.stream()
            .filter(i -> i ? filter.contains("TRUE") : filter.contains("FALSE"))
            .collect(Collectors.toList());
    System.out.println(collect);
} else { System.out.println(values);}

With filter values TRUE, FALSE or TRUE,FALSE I get the desired result [true, true, true], [false, false, false] and [true, false, true, false, false, true]. In case of an empty filter, the list should be returned as is. "TRUE" or "FALSE" may represent any String..

Is there a more elegant way to implement?

Upvotes: 0

Views: 86

Answers (3)

Bohemian
Bohemian

Reputation: 425188

You can:

  1. test for emptiness inside the predicate (unmeasurably small performmance cost)
  2. use a ternary for the contains value

Thus eliminating the if-else and the extra call to contains():

List<Boolean> collect = values.stream()
        .filter(i -> filter.isEmpty() || filter.contains(i ? "TRUE" : "FALSE"))
        .collect(Collectors.toList());

System.out.println(collect);

Upvotes: 1

Joe
Joe

Reputation: 1342

I'm not sure what the goal is here but elegance could be in the eye of the beholder so, here you go.

public static void main(String[] args) {
    System.out.println(go(
            Arrays.asList(true, false, true, false, false, true), 
            Arrays.asList("TRUE")));
}

static List<Boolean> go(final List<Boolean> values, final List<String> filter) {
    if (filter.isEmpty())
        return values;
    return values
            .stream()
            .filter(i -> filter.contains(i.toString().toUpperCase()))
            .collect(Collectors.toList());
}

Upvotes: 0

Andreas
Andreas

Reputation: 159135

If the filter can truly only be the 4 valid combinations, then you can cheat:

if (filter.size() == 1) {
    Boolean removeTrue = filter.contains("FALSE");
    values.removeIf(removeTrue::equals);
}
System.out.println(values);

Upvotes: 2

Related Questions