使用for each循环来查找数组列表中的两个元素
我需要帮助为每个循环编写一个循环,用于搜索名为peoplelist类型的数组列表的人员列表。循环需要搜索数组中的字符串邮政编码和字符串名称。如果找到它,则需要返回它们的ID;如果没有,则返回null。任何形式的帮助都会很棒!使用for each循环来查找数组列表中的两个元素
//In case multiple persons match :)
List<String> result = new LinkedList<String>();
for (People person : peopleList) {
if (person.getName().equals(name) && person.getPostcode().equals(postCode))
result.add(person.getId());
}
if(result.isEmpty()){
return null;
}else{
return result;
}
非常感谢! – Jimmy 2011-03-22 11:53:46
需要做出很多假设你的类,但这样的事情就够了:
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?
随着“两个要素”,你的意思是“某个类的两个属性”?如果是这样,沿着这些路线的东西会做:
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
如果该类People
是这样写一个Java bean(即标准getter方法),这样的事情会做的工作:
for (People person : peopleList) {
if (person.getName().equals(name) && person.getPostcode().equals(postCode))
return person.getId();
}
return null;
如果某人的姓名或邮编可能为null
,则可能需要翻转equals
调用以避免空指针异常(例如name.equals(person.getName())
而不是person.getName().equals(name)
)。
btw Person
将是一个更好的名字。
People foundPerson;
for (People eachPeople : peoplelist)
{
if (Integer.valueOf(eachPeople.getID()) == 10054
&& "Jimmy".equals(eachPeople.getName()))
{
foundPerson= eachPeople;
break;
}
}
假设你有一个Person
豆,然后如果你想检索其postcode
和name
匹配一些值的Person
任何情况下,你可以做这样的事情:
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;
}
下一页时间,你可能想向我们展示你的代码,所以我们可以帮助你理解你做错了什么:)
好的抱歉,我是新来这个网站,我想只是说我做了这个尝试,但这是我第一次使用for-each循环,我找不到任何简单的例子来帮助我理解:) – Jimmy 2011-03-22 12:00:47
这个功课是? – SWeko 2011-03-22 11:31:24
它看起来好像不想在数组列表中找到“两个元素”,而是数组列表中所有“People”元素的“两个属性”。正确?你能让我们知道你的'人民'班是怎么样的吗? – MarcoS 2011-03-22 11:33:35
是的,我的意思是属性抱歉。将代码提供给我2秒 – Jimmy 2011-03-22 11:39:55