Java 获取arrayList中的特定对象
如何在学校列表中获取Java 获取arrayList中的特定对象,java,android,arraylist,Java,Android,Arraylist,如何在学校列表中获取列表数据 List<School> schools = new ArrayList<School>(); School school_aaa = new School(); school_aaa.setName( "aaa" ); Student student_aaa_001 = new Student(); student_aaa_001.setName( "aaa_001" ); student_aaa_001.setAge( 17 );
列表
数据
List<School> schools = new ArrayList<School>();
School school_aaa = new School();
school_aaa.setName( "aaa" );
Student student_aaa_001 = new Student();
student_aaa_001.setName( "aaa_001" );
student_aaa_001.setAge( 17 );
student_aaa_001.setId( 21345678 );
Student student_aaa_002 = new Student();
student_aaa_002.setName( "aaa_002" );
student_aaa_002.setAge( 13 );
student_aaa_002.setId( 6789876 );
List<Student> students = new ArrayList<Students>();
students.add( student_aaa_001 );
students.add( student_aaa_002 );
school_aaa.setStudents( students );
schools.add("aaa");
List schools=new ArrayList();
学校学校=新学校();
学校名称(“aaa”);
Student Student_aaa_001=新学生();
学生名称(“aaa_001”);
学生组(17);
学生组001.setId(21345678);
学生学生_aaa_002=新学生();
学生名称(“aaa_002”);
学生组(13);
学生编号(6789876);
List students=new ArrayList();
学生。添加(学生\ aaa \ 001);
学生。添加(学生\ aaa \ 002);
学校设置学生(学生);
学校。加上(“aaa”);
我只有学校的名字。
但它不能使用indexOf方法。
因为那只是同一个物体
这意味着我需要获取学校对象,而不是学校名称
我如何找到学校物品
以下是数据类型
Student.java
School.java
Java8的流式API通过过滤为您提供了一个非常简洁的语法。如果您可以假设只有一所学校有一个给定的名称,您可以使用以下方法: 如果你不能,你将不得不处理学校的子列表:
List<School> aaaSchools = schools.stream()
.filter(x -> x.getName().equals("aaa"))
.collect(Collectors.toList());
List aaaSchools=schools.stream()
.filter(x->x.getName().equals(“aaa”))
.collect(Collectors.toList());
用于(int-cnt=0;cnt
您似乎正在尝试在学校列表中查找特定的学校。如果这不是你想做的,请让我知道
我会这样做:
public School findSchool(String schoolName)
{
// Goes through the List of schools.
for (School i : schools)
{
if (i.getName.equals(schoolname))
{
return i;
}
}
return null;
}
学校。获取(i);它会给你一个很好的解释,谢谢你的评论。若你们只有学校名称,你们怎么知道索引?它需要索引号才能使用schools.get(index)。
for(int cnt = 0; cnt < schools.size; cnt++){
if(schools.get(cnt).getSchooname.equalIgnorecase("Your school name")){
// cnt is your index
}
}
public School findSchool(String schoolName)
{
// Goes through the List of schools.
for (School i : schools)
{
if (i.getName.equals(schoolname))
{
return i;
}
}
return null;
}