Thamiar
Thamiar

Reputation: 610

Apply filter to stream if certain condition is fullfilled

How can I add the filter to a stream depending on the boolean value?

for example variable = false (I do not add filter) and if variable = true I add it

list.stream()
  .filter(I want do add or not add this filter depending on boolean variable)
  .map(mapping method).collect(Collectors.toList)

Upvotes: 1

Views: 879

Answers (3)

fps
fps

Reputation: 34480

Stream.filter is an intermediate operation. This means that it returns another Stream instance, so you can use common, old-fashioned local variables:

Stream<Whatever> s = list.stream();
if (variable) {
    s = s.filter(x -> /* some condition to filter elements */);
}
List<SomethingElse> result = s.map(x -> /* map whatever to something else */)
                              .collect(Collectors.toList());

Upvotes: 1

Jonck van der Kogel
Jonck van der Kogel

Reputation: 3293

Here is how I would do this. You create a function that returns a Predicate. Based on your parameter it either applies the function that you pass in or you create a no-op Predicate (i.e. one that always evaluates to true):

public <T> Predicate<T> createPredicate(boolean shouldApply, Function<T, Boolean> fun) {
    return (t) -> shouldApply ? fun.apply(t) : true;
}

Here are some tests to show how you would use something like this:

private static final List<Integer> sampleList = List.of(1, 2, 3, 4, 5, 6);

@Test
public void shouldNotApplyFilter() {
    List<Integer> result = sampleList
            .stream()
            .filter(createPredicate(false, i -> i % 2 == 0))
            .map(i -> i * 2)
            .collect(Collectors.toList());

    Assertions.assertEquals(6, result.size());
}

@Test
public void shouldApplyFilter() {
    List<Integer> result = sampleList
            .stream()
            .filter(createPredicate(true, i -> i % 2 == 0))
            .map(i -> i * 2)
            .collect(Collectors.toList());

    Assertions.assertEquals(3, result.size());
}

Upvotes: 0

0TTT0
0TTT0

Reputation: 1332

I can think of two ways to do this.

I think that the simplest is just to check the condition and write out the functional programming construct accordingly.

if (var) list.stream().filter().map().collect(Collectors.toList)
else list.stream().map().collect(Collectors.toList)

Otherwise, do your conditional check in the filter itself. In the filter, we are always returning true if the variable is true thus nullifying the behavior of the filter, if variable is false then we do the actual filter logic.

list.stream().filter(()=>{
if (!var) return true;
else doFilter();
}).map().collect(Collectors.toList)

Upvotes: 2

Related Questions