1

I have 3 filters but they are not always filled with values!

for example:

a=1, b=2, c=null

and I have this for filtering:

myList.stream()
      .filter(item->item.a == a)
      .filter(item->item.b == b)
      .filter(item->item.c == c)
      .Collect(collection.asList);

But it does not work for me. I need the c parameter and its filter to be ignored if my input for c is null like this:

 myList.stream()
       .filter(item->item.a == a)
       .filter(item->item.b == b)
       .Collect(collection.asList);

And whenever each other filter is null, it should be removed from filter's chain like c in previous example.

5
  • What's the declared data type of item.c and of input c? Commented Nov 25, 2019 at 16:06
  • 2
    So change the implementation of your predicate so that it always returns true if c is null. And please, when you ask a question, post real code. Not pseudo-code. Commented Nov 25, 2019 at 16:08
  • 3
    So .filter(item -> item.c == null || item.c == c)? Commented Nov 25, 2019 at 16:41
  • Thanks in advance @ernest_k. It's String Commented Nov 26, 2019 at 7:05
  • Thanks@Holger, I think its inverse of my problem, the matter is null input! not the null attribute of object Commented Nov 26, 2019 at 7:10

2 Answers 2

3

For the condition to become valid, it needs the constant to be null or the item's value equal to the constant. This would look like:

myList.stream()
      .filter(item -> a == null || item.a == a)
      .filter(item -> b == null || item.b == b)
      .filter(item -> c == null || item.c == c)
      .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

2

My version:

myList.stream()
        .filter(item -> a == null ? true : item.a.equals(a))
        .filter(item -> b == null ? true : item.b.equals(b))
        .filter(item -> c == null ? true : item.c.equals(c))
        .collect(Collectors.toList());

When a filter method returns true, it doesn't filter anything out. If a, b and c are references, as a rule you should use equals() for comparison, not ==.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.