我正在努力寻找一个相关的答案来解决我的问题。我有一个数组列表:
List<Teacher> teacherList = new ArrayList<Teacher>(11);
teacher类有一个name属性。我想浏览一下教师列表,看看是否有与用户输入的姓名匹配的姓名。
举个例子,
Scanner teacherNameScanner = new Scanner (System.in);
System.out.println("What is the teachers name");
teacherName = teacherNameScanner.nextLine();
/* Here I want to scan through the teacherList and see whether the name entered
matches the name of any of the teachers. If it does not match I want to tell the
user to enter a correct name */
发布于 2018-10-18 06:56:52
这真的取决于你的用例,名称是否区分大小写?此外,您可能想要考虑修剪空格。然后创建一个集合nameSet,您可以在其中对现有名称执行get操作,这是一个O(1)操作。同样,对于这个问题有很多解决方案,除非你描述确切的用例,比如你是想用姓名还是id(通常是id)来识别老师,很难想出正确的解决方案。而是你所描述的HashSet应该做的事情。
Set<String> nameSet = new HashSet<String>();
if (nameSet.contains(teacherName))
do what you want
else
other case
发布于 2018-10-18 17:28:23
如果您使用的是Java 8或更高版本,则可以使用:
teacherList.stream().anyMatch(teacher -> teacher.getName().equals(name));
其中name是您要搜索的名称。
发布于 2018-10-18 06:56:09
for each
就是医生开的菜(除非你有什么特别的菜,否则你可以用它来做一个更有效的搜索)。
private Teacher findTheTeacher(ArrayList<Teacher> teacherList, String teacherName) {
for (Teacher teacher : teacherList) {
if (teacher.name.equals(teacherName)) {
return teacher;
}
}
return null; // or something like this
}
https://stackoverflow.com/questions/52864625
复制相似问题