user1413969
user1413969

Reputation: 1291

Testing for value in a list java

I currently have a list of Site objects as my Sites object:

List<Site> sites = new LinkedList();

Site is made up of:

String url;
String id;
Host host;

I want to write a method that tests to see if my any of the 'Site' values in site contains the url String or the id String.

I can't use the contains method for this, since I don't care about the host value.

Is there a easier way to do it via Collections besides writing something like:

public boolean checkValues(String url, String id) {
    for (Site : this.sites) {
          // Check if the url, id is in the site
}

Upvotes: 0

Views: 174

Answers (3)

Makoto
Makoto

Reputation: 106389

You can do it with either Guava, as explained in another answer, or natively within Java 8. This makes use of a lambda function and a Stream object.

Suppose we only care about IDs that contain the string 4 or URLs that contain the string 6. Here's one approach to that.

This is the more verbose approach, combining Java 8 lambdas and old-school iteration.

final Stream<Site> filter =
        siteList.stream().filter(site -> site.getId().contains("4") || site.getUrl().contains("6"));
for(Iterator<Site> filterIter = filter.iterator(); filterIter.hasNext(); ) {
    Site next = filterIter.next();
    System.out.println(next);
}

Here's a more succinct way, using the forEach Consumer:

siteList.stream().filter(
    site -> site.getId().contains("4") ||
    site.getUrl().contains("6")).forEach((site) -> System.out.println(site));

Here's the most terse approach, using the System.out::println method reference.

siteList.stream().filter(
        site -> site.getId().contains("4") ||
                site.getUrl().contains("6"))
                 .forEach(System.out::println);

Upvotes: 1

GeZo
GeZo

Reputation: 96

Use Guava collection filter predicate

Iterable<Person> filtered = Iterables.filter(allPersons, new Predicate<Person>() {
    @Override
    public boolean apply(Person p) {
        return acceptedNames.contains(p.getName());
    }
});

There is same question: Filtering a list of JavaBeans with Google Guava

Upvotes: 1

Hirak
Hirak

Reputation: 3649

No there isn't any such method in Collections yet. I am not sure if there are any 3rd party solutions.

Alternatively, the following can be done (if usecase permits ofcourse)

public class Site {
    String url;
    String id;
    String host;

    boolean contains(String str) {
        if(url.contains(str) || id.contains(str)) return true;
        return false;
    }
}

=====================

for (Site site : sites) {
    if(site.contains(s)) {
//TODO
    }
}

Upvotes: 2

Related Questions