Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java stream list of filters

Let's say I've got a list of Strings and I want to filter them by the list of filtering Strings. For the list which consists of: "abcd", "xcfg", "dfbf"

I would precise list of filtering Strings: "a", "b", and after something like filter(i->i.contains(filterStrings) I would like to receive list of "abcd", "dfbf", And for a list of filtering Strings: "c", "f" I would like to reveive list of "xcfg" and "dfbf".

List<String> filteredStrings = filteredStrings.stream()
            .filter(i -> i.contains("c") || i.contains("f")) //i want to pass a list of filters here
            .collect(Collectors.toList());

Is there an other way of doing this instead of expanding body of lambda expression and writing a function with a flag which will check every filter?

like image 249
steve1337 Avatar asked Oct 19 '25 02:10

steve1337


1 Answers

You should instead be performing a anyMatch over the list to match from:

List<String> input = Arrays.asList("abcd", "xcfg", "dfbf"); // your input list
Set<String> match = new HashSet<>(Arrays.asList("c", "f")); // to match from
List<String> filteredStrings = input.stream()
        .filter(o -> match.stream().anyMatch(o::contains))
        .collect(Collectors.toList());
like image 165
Naman Avatar answered Oct 21 '25 15:10

Naman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!