gpt4 book ai didi

java - 如何以正确的方式过滤 ArrayList 的内容?

转载 作者:行者123 更新时间:2023-12-02 09:59:20 26 4
gpt4 key购买 nike

我正在寻找一种更好的方法来过滤 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);

它正在起作用,但我相信有更好的方法来实现这一目标

最佳答案

您可以使用这种方法:

class Student { String name; boolean old; boolean stupid; }

List<Student> students = initializeListOfStudents();

// alter these flags accordingly to your needs
Boolean old = null;
Boolean stupid = true;

// then do the filter
List<Student> allStupids = students.stream()
.filter(it -> (old==null || it.old == old) && (stupid==null || it.stupid==stupid))
.collect(Collectors.toList());

关于java - 如何以正确的方式过滤 ArrayList 的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55749088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com