0

I'm trying to make a filter with lambda. There is a list of string, which contains values, that should be sorted out and there's the other list, which contains different values (that's the one, that should be filtered). So what I've been trying to do is:

stringList = stringList.stream()
       .filter(e ->toBeSortedOutList.forEach(outSorted->!e.startsWith(outSorted)))
       .collect(Collectors.toList());

Unfortunately, I am allways getting the error, that boolean can't be converted to void. So what I wanted to know is, why that I am getting this error and if it's possible to filter by iterating trough a list and using its values for the filter? Thanks for your answers!

3
  • 1
    What exactly do you want to do? Could you provide a sample input / output? Commented Jan 11, 2016 at 9:46
  • 1
    Could you provide an example of such lists and the output you're trying to get for them? Commented Jan 11, 2016 at 9:47
  • 4
    Generally, you should try to find out, what a method does, before using it. There is no reason to assume that a void method, like forEach, can be used as a predicate. I hope, you've already heard about that thing called API documentation Commented Jan 11, 2016 at 9:53

1 Answer 1

8

Use noneMatch:

stringList = stringList.stream()
   .filter(e ->toBeSortedOutList.stream().noneMatch(outSorted->e.startsWith(outSorted)))
   .collect(Collectors.toList());

In general avoid using forEach unless you need an explicit side-effect (like output to System.out). Usually there are better alternatives to solve your problem.

By the way you can also modify your list in-place using removeIf:

stringList.removeIf(e -> toBeSortedOutList.stream()
                         .anyMatch(outSorted->e.startsWith(outSorted)));
Sign up to request clarification or add additional context in comments.

2 Comments

outSorted->e.startsWith(outSorted)) can also be expressed as a method reference e::startsWith
@Misha, agreed, I would use method reference in my code. However this might look cryptic for the beginners.

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.