Java Search Objects

Consider a scenario where you need to search through a list of objects for a particular value. For example, There is an ArrayList of Employees as follows.

    ArrayList al = new ArrayList();
    al.add(new Employee("100", "jack"));
    al.add(new Employee("102", "rose"));
    al.add(new Employee("103", "rock"));
    al.add(new Employee("104", "lily"));

How will you retrieve the Employee objects with same name as "lily" ? There is a way in arraylist to search for a particular object in the list using ArrayList.containst(obj) method. But in our case we need to retrieve the list of objects which has same value for a particular attribute or member variable .

Here is a generalized solution using java reflection API.
Code

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package in.techdive.java.examples;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * This class is used to search through a list of objects for a particular value
 */

public class SearchObjectImpl
{
    public List getObjectFromList(List ls, String className, String key,
            String value)
    {
        List objLst = ls;
        List result = new ArrayList();
        Iterator it = objLst.iterator();
        Class c = null;
        while (it.hasNext())
        {
            Object obj = it.next();
            c = obj.getClass();
            Field[] flds = c.getDeclaredFields();
            String fValue = null;
            for (Field f : flds)
            {
                if (f.getName().equalsIgnoreCase(key))
                {
                    try
                    {
                        fValue = (String) f.get(obj);
                        if (fValue.equalsIgnoreCase(value))
                        {
                            result.add(obj);
                        }
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }
        return result;
    }

    /**
     * Main method for testing
     *
     * @param args Command line arguments
     */

    public static void main(String[] args)
    {
        SearchObjectImpl sI = new SearchObjectImpl();
        ArrayList al = new ArrayList();
        al.add(new Employee("100", "jack"));
        al.add(new Employee("102", "rose"));
        al.add(new Employee("103", "rock"));
        al.add(new Employee("104", "lily"));
        al.add(new Employee("105", "lily"));
        List<Employee> eList = (List<Employee>) sI.getObjectFromList(al,
                "in.techdive.java.examples.Employee", "empName", "lily");
        if (eList != null && eList.size() > 0)
        {
            for (Employee e : eList)
            {
                System.out.println("Employee object search is " + e.getEmpId());
            }
        }
        else
        {
            System.out.println("Employee object does not exist ");
        }
    }
}

Consider the method getObjectFromList() in the above class. The method arguments are
list - the list from which the objects are to be searched.
className - name of the class whose attribute values are to be searched,
key - name of the class attribute .
value - value of the class search attribute.

Once the above arguments are passed , the search method executes in the following way.

1.) Iterates through the List one by one.
2.) For every object in the list it gets the list of fields (or member variables with values) for that object.
3.) Each field in the current object is iterated and if there is any match with the given (key,value) pair , then that particular object is added to the results list.

Now its time to test the above search method .

    public static void main(String[] args)
    {
        SearchObjectImpl sI = new SearchObjectImpl();
       
        ArrayList al = new ArrayList();
        al.add(new Employee("100", "jack"));
        al.add(new Employee("102", "rose"));
        al.add(new Employee("103", "rock"));
        al.add(new Employee("104", "lily"));
        al.add(new Employee("105", "lily"));.
       
        List<Employee> eList = (List<Employee>) sI.getObjectFromList(al,
                "in.techdive.java.examples.Employee", "empName", "lily");
        if (eList != null && eList.size() > 0)
        {
            for (Employee e : eList)
            {
                System.out.println("Employee object search is " + e.getEmpId());
            }
        }
        else
        {
            System.out.println("Employee object does not exist ");
        }
    }

Output

Employee object search is 104
Employee object search is 105
Technology: 

Search