简体   繁体   中英

Checking that a field in a List of Objects has a certain value?

I have a list of Person Objects:

List<Person> allPersons = new ArrayList<Person>();

The Person object has a field called Address .

I would like to check that at least one Person in the list has a certain address How can I do this?

I know that there is a .containsValue() method when using a HashMap, but is there anything similar for an ArrayList ?

Edit: please note that I am searching for a specific field value within each object, not the object itself?

You have to iterate over the List one way or another.

One convenient way to do it is with Java8 Streams :

boolean found = allPersons.stream().anyMatch(p->p.getAddress().equals(someAddress));

You can use asLazy() and collect() from Eclipse Collections :

If you can use the MutableList interface:

MutableList<Person> allPersons = Lists.mutable.empty();
boolean found =
    allPersons.asLazy().collect(Person::getAddress).contains(someAddress);

If you can't change the type of allPersons from List :

List<Person> allPersons = new ArrayList<>();
boolean found = 
    LazyIterate.collect(allPersons, Person::getAddress).contains(someAddress);

Note: I am a contributor to Eclipse Collections.

If you plan on making this check often, load the addresses in the Set<String> on which you can then call the contains method:

Set<String> allAddresses = 
   allPersons.stream().map(Person::getAddress).collect(toSet());
// ...
boolean found = allAddresses.contains(someAddress);

You could simply do while + iterator loop

boolean found = false;
Iterator it = allPersons.iterator();
Person currentPerson = null;

while(!found && it.hasNext()){
    currentPerson = it.next();
    if(currentPerson != null && paramAdress.equals(person.getAddress()){
        found = true;
    }
}

As a complement, if you don't feel comfortable with Eran's answer (which is the best possible answer) or you can't use Java 8, just create a method like:

public boolean checkAdress(String adress)
{
    boolean found = false;
    for(int i = 0; i < allPersons.size() && !found; i++)
        found = allPersons.get(i).getAdress().equals(adress);
    return found;
}

This is what I used to do before Java 8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM