I need help writing a for each loop which searches through an array list called peoplelist of type people. The loop needs to search for the values String postcode and String name in the array. It then needs to return their ID if it is found, and null if it is not. Any sort of help would be great!
6 Answers
If the class People is written like a Java bean (i.e. with standard getter methods), something like this would do the job:
for (People person : peopleList) {
if (person.getName().equals(name) && person.getPostcode().equals(postCode))
return person.getId();
}
return null;
If a person's name or postcode can be null, you may want to flip the equals calls to avoid null pointer exceptions (e.g. name.equals(person.getName()) instead of person.getName().equals(name)).
Btw Person would be a better name.
Comments
Need to make a lot of assumptions about your classes, but something like this should suffice:
for (People person : peoplelist) {
if (person.getPostCode().equals(postcode) && person.getName().equals(name)) {
return person.getId();
}
}
// deal with not being found here - throw exception perhaps?
Comments
With “two elements”, do you mean “two attributes of some class”? If so, something along these lines would do:
String id = null;
for(People p : peoplelist) {
if(somePostcode.equals(p.postcode) && someName.equals(p.name)) {
id = p.id;
break; // no need to continue iterating, since result has been found
}
}
// result “id” is still null if the person was not found
Comments
Assuming you have a Person bean, then if you want to retrieve all instances of Person whose postcode and name match some values, you may do something like this:
public List<Person> searchFirst(List<Person> persons, String postcode, String name) {
List<Person> matchingPersons = new ArrayList<Person>();
for (Person person : persons) {
if (person.getPostcode().equals(postcode) && person.getName().equals(name))
matchingPersons.add(person);
}
return matchingPersons;
}
Next time, you may want to show us your code, so we can help you in understanding what you're doing wrong :)
Peopleelements in an array list. Correct? Could you let us know how yourPeopleclass look like?Peoplewhosepostcodeandnamematch the ones you're searching for, or do you want to return all instances ofPeoplewhosepostcodeandnamematch the ones you're searching for?