【发布时间】:2019-09-08 23:19:17
【问题描述】:
我正在努力寻找一种更好的方法来过滤 ArrayList 的内容
例如,这个程序有一个名为“students”的主 ArrayList,然后我从这个列表的内容中创建了其他子列表(oldStudents、youngStudents、stupidStudents、smartStudents。目标是根据学生的用户选择过滤 ArrayList (年轻、年老、聪明或愚蠢)
ArrayList<String> students = new ArrayList<String>();
ArrayList<String> smartStudents = new ArrayList<String>();
ArrayList<String> stupidStudents = new ArrayList<String>();
ArrayList<String> oldStudents = new ArrayList<String>();
ArrayList<String> youngStudents = new ArrayList<String>();
//adding all the students to students list
Collections.addAll(students, "Ram", "Mohan", "Sohan", "Rabi", "Shabbir","Jack", "Johnson", "Peter", "Despina", "Me");
//adding young students to youngStudents list
Collections.addAll(youngStudents, "Ram", "Mohan", "Sohan", "Rabi", "Shabbir");
//adding smart students to oldStudents list
Collections.addAll(oldStudents, "Jack", "Johnson", "Peter", "Despina", "Me");
//adding smart students to smartStudents list
Collections.addAll(smartStudents, "Sohan", "Rabi", "Peter", "Despina");
//adding smart students to stupidStudents list
Collections.addAll(stupidStudents, "Ram", "Mohan", "Shabbir","Jack", "Johnson", "Me");
Scanner input = new Scanner(System.in);
String uInput = "";
System.out.print("This is a students search engine, write 'young' for younger students and 'old' for older ones ");
uInput = input.nextLine();
if(uInput.equals("young")) {
students.removeAll(oldStudents);
} else if (uInput.equals("old")) {
students.removeAll(youngStudents);
}
System.out.print("now write 'Smart' for smarter students and 'Stupid' for less smart students ");
uInput = input.nextLine();
if(uInput.equals("smart")) {
students.removeAll(stupidStudents);
} else if (uInput.equals("Stupid")) {
students.removeAll(smartStudents);
}
System.out.println(students);
它正在工作,但我相信有更好的方法来实现这一点
【问题讨论】:
-
第一次将所有这些列表插入学生列表中...
-
除非您需要在类中包含其他功能,否则最好分配给接口类型。您还可以通过执行
List<String> stupid = new ArrayList<>(List.of("stupid1", "stupid2"));之类的操作来创建可变列表。还有其他使用streams() 和收集器的方法。
标签: java search arraylist filter