我正在尝试根据用户输入查找特定对象。用户输入姓名和性别,然后程序应该搜索 ArrayList 并查看是否有匹配的姓名和性别。 ArrayList 中的对象有 3 个实例变量,但程序只搜索 2 个。如何在 ArrayList 中只搜索选定的几个特征?
在我的程序中,我有:
int nameListLength = nameList.size();
.
.
.
boolean done = false;
while (!done) {
System.out.println ("Please enter a name:");
String searchName = input.nextLine();
if (searchName.equals("DONE")) {
done = true;
} else {
System.out.println ("Please enter a gender:");
String searchGender = input.nextLine();
// Search the ArrayList.
for (int i = 0; i < nameListLength; i++) {
// See if the gender is in the ArrayList
if (searchGender.equals(nameList.get(i).getGender())) {
// See if the name matches the gender in the ArrayList
if (searchName.equals(nameList.get(i).getName())) {
System.out.println ("Match found");
}
}
}
}
}
其中nameList是ArrayList的名称,getName()是返回对象中存储的名称的方法名称,getGender()是返回对象中存储的性别的方法名称。我放入调试语句以确定 ArrayList 是否正确存储信息,我只是在弄清楚如何搜索我要查找的内容时遇到问题。我知道有一个 contains(Object o) 方法,但我不确定是否可以在这里实现,因为即使该对象包含 3 条数据,我也只需要匹配该对象的 2 个特征。
最佳答案
一般来说,你的代码看起来不错,即使它有点凌乱。您声称它不起作用,但我看不到明显的错误,因此我会仔细检查输入列表和搜索词(例如案例特异性)。
不要为了能够使用 contains 而重写 equal,因为这意味着您始终将仅通过这两个属性来比较对象。
您可以考虑使用新的 Stream API,它有几个方法可以完全满足您的需求:
List<Yourtype> found = list.stream().filter(u -> u.getName().equals(searchName) && u.getGender().equals(searchGender)).collect(Collectors.toList());
检查是否有匹配的元素
boolean isMath = list.stream().anyMatch(u -> u.getName().equals(searchName) && u.getGender().equals(searchGender));
获取第一个匹配:
Yourtype match = list.stream().findFirst(u -> u.getName().equals(searchName) && u.getGender().equals(searchGender)).get();
关于java - 在 ArrayList Java 中搜索特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29525285/