Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter list using Predicate [duplicate]

Tags:

java

private static class FilterByStringContains implements Predicate<String> {
        private String filterString;
        private FilterByStringContains(final String filterString) {
            this.filterString = filterString;
        }
        @Override
        public boolean apply(final String string) {
            return string.contains(filterString);
        }
    }

I have a list of Strings, I want to filter it by the specified String so the returned value contains a list of only the specified strings. I was going to use a predicate as above but not sure how to apply this to filter a list

like image 369
RandomUser Avatar asked Mar 26 '12 18:03

RandomUser


People also ask

How do I filter a list based on another list in Java 8?

One of the utility method filter() helps to filter the stream elements that satisfy the provided criteria. The predicate is a functional interface that takes a single element as an argument and evaluates it against a specified condition.

How will you run a filter on a collection?

You can filter Java Collections like List, Set or Map in Java 8 by using the filter() method of the Stream class. You first need to obtain a stream from Collection by calling stream() method and then you can use the filter() method, which takes a Predicate as the only argument.


2 Answers

I'm assuming the Predicate here is from Guava? If so, you could use Iterables.filter:

Iterable<String> filtered = Iterables.filter(original, predicate);

Then build a list from that if you wanted:

List<String> filteredCopy = Lists.newArrayList(filtered);

... but I'd only suggest copying it to another list if you actually want it as a list. If you're just going to iterate over it (and only once), stick to the iterable.

like image 167
Jon Skeet Avatar answered Oct 06 '22 00:10

Jon Skeet


How about using Guava's filter method or Apache commons' filter method? Guava's method returns a view of the collection, whereas Apache Commons' modifies the collection in-place. Don't reinvent the wheel!

like image 21
Óscar López Avatar answered Oct 06 '22 02:10

Óscar López