bubu uwu
bubu uwu

Reputation: 483

get a specific object in arrayList

How can I get a List<Student> data in School list?

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");

I only have school name. But it couldn't use indexOf method. because that's only works same object.

that means I need to get School object not school name.

how do I find School object.

here are DataTypes.

Student.java enter image description here

School.java enter image description here

Upvotes: 3

Views: 4922

Answers (3)

Hatefiend
Hatefiend

Reputation: 3596

It seems like you are trying to find a specific school in the list of schools. If this is not what you are trying to do, please let me know.

Here's how I would do it:

public School findSchool(String schoolName)
{
    // Goes through the List of schools.
    for (School i : schools)
    {
        if (i.getName.equals(schoolname))
        {
            return i;   
        }   
    }
    return null;
}

Upvotes: 4

Pavya
Pavya

Reputation: 6025

for(int cnt = 0; cnt < schools.size; cnt++){
  if(schools.get(cnt).getSchooname.equalIgnorecase("Your school name")){
    // cnt is your index
  }    
}

Upvotes: 2

Mureinik
Mureinik

Reputation: 311073

Java 8's streaming API gives you a pretty neat syntax to doing so, by filtering. If you can assume that there's only one school with a given name, you could use the findFirst() method:

School aaaSchool = schools.stream()
                          .filter(x -> x.getName().equals("aaa"))
                          .findFirst()
                          .orElse(null);

If you can't, you'll have to do with a sub-list of schools:

List<School> aaaSchools = schools.stream()
                                 .filter(x -> x.getName().equals("aaa"))
                                 .collect(Collectors.toList());         

Upvotes: 4

Related Questions