user6602355
user6602355

Reputation:

Searching an object stored in arraylist by multi word search key

I am developing a search algorithm. In which we have an ArrayList of student object. And we have to search students from the ArrayList. The attributes of student class are name, city, country and phone number. The search should work such that if we type name, city, country or number we should get the list of the student objects matching the search. soppose, if we type "john" in search then we should get a list of the student objects whose names are john. And if the search query has more than one words (like "john brazil") then we should get the list of all the student objects in which the name is john and country is brazil. I am not getting the proper output, In the list I am getting all the objects where name is john and all the objects where the country is brazil. Getting (name || country) but I need (Name && country). Any help will be appreciated. Thanks in advance.

The code is as below:

public Class Student {
    private String first_name;
    private String last_name;
    private String city;
    private String country;
    private int phone_number; 
}

public ArrayList<Student> searchMethod() {

    ArrayList<Student> initial_result_list= new ArrayList<Student>;

    for (Student student : student_list) {
        for (String search : array_of_search_words) {
            if((null!=student.getName() && student.getName().contains(search))
            || (null!=student.getCity() && student.getCity().contains(search))
            || (null!=student.getCountry() && student.getCountry().contains(search))
            || (null!=student.getCity() && student.getCity().contains(search))
            || (null!=student.getPhone_number() && student.getPhone_number().contains(search))) {

                if(!initial_result_list.contains(student)) {
                    initial_result_list.add(student);
                }
            }
        }
    }
    return initial_result_list;
}

Upvotes: 1

Views: 420

Answers (1)

Sumeet
Sumeet

Reputation: 8292

You must make sure that each of the words in array_of_search_words has been matched by some of the attribute of the Class Student.

For this change your logic to:

for (Student student : student_list) {
    bool matched = false;
    for (String search : array_of_search_words) {
        if((null!=student.getName() && student.getName().contains(search))
        || (null!=student.getCity() && student.getCity().contains(search))
        || (null!=student.getCountry() && student.getCountry().contains(search))
        || (null!=student.getCity() && student.getCity().contains(search))
        || (null!=student.getPhone_number() && student.getPhone_number().contains(search))) {    
        matched = true;           
        }
        else {matched = false;break;}

    }
    if(!initial_result_list.contains(student) && matched)
                initial_result_list.add(student);
}

Upvotes: 0

Related Questions