Iterating through the list of type T and searching for a value


Basically I want to write a function that takes list of type T and searches for a given value with given field name.

public static boolean listContains( List<T> source, String field, String value ) {
     for ( T t : source ) {
         if ( t.get[field]().equals(value) ) // the getField needs to be dynamic. reflection only way? 
             return true;
     return false;

Any ideas?

If the field (getField) does not exist, then it should simply return false.

Your method is not generic and since it should accept any type of object you can change list type to List<?> source.

public static boolean listContains(List<?> source, String field, String value) {
    for (Object obj : source ) {
        try {
            Field f = obj.getClass().getDeclaredField(field); //get the field using name
            Object val = f.get(obj); //the value of the field in the current object
            if(value.equals(val)) { //if it equals to passed value
                return true;        //return true
        } catch (NoSuchFieldException e) { //if the object doesn't have the field
            return false;                  //return false
        } catch (Exception e) { //their are other exceptions
            throw new RuntimeException(e); //how ever you want to handle
    return false; 

You could create a supertype and make your method as follows (to avoid using reflection) -

public static boolean listContains(List<? extends MyObject> source, String value) {        
    for (MyObject obj : source ) {
        //... value.equals(obj.getField())

But the problem with that approach is that it would be constrained to certain field(s).

You should be able to create a generic entity A and have a getField method in that entity. Thereafter, use List < T extends A > to ensure that getField can be used.

Alternatively, you can use reflection to check if the getField method exists. But this would be slow.

By : Vivek

Consider the flollwoing Example.

        public class BST<E extends Comparable<E>> 
            extends AbstractTree<E> {
            protected TreeNode<E> root;
            protected int size = 0;

           /** Create a default binary tree */
             public BST() {

           /** Create a binary tree from an array of objects */
          public BST(E[] objects) {
          for (int i = 0; i < objects.length; i++)

          @Override /** Returns true if the element is in the tree */
          public boolean search(E e) {
          TreeNode<E> current = root; // Start from the root

          while (current != null) {
          if (e.compareTo(current.element) < 0) {
          current = current.left;
          else if (e.compareTo(current.element) > 0) {
          current = current.right;
          else // element matches current.element
          return true; // Element is found

          return false;
By : zee

This video can help you solving your question :)
By: admin