1

I have the below class with the fields name and id -

    public class MyObj {
        private String name;
        private String id;
        //getters and setters + toString implementation
    }

In my main method, I am creating a list of MyObjand adding elements to the list.

public static void main(String[] args) {
    List<MyObj> myList = new ArrayList<MyObj>();
    MyObj myObj1 = new MyObj();
    myObj1.setName("test");
    myObj1.setId("123");
    myList.add(myObj1);

    MyObj myObj2 = new MyObj();
    myObj2.setName("testOne");
    myObj2.setId("456");
    myList.add(myObj2);
   }

When I iterate through the list, and print the contents, I have this -

    MyObj [name=test, id=123]
    MyObj [name=testOne, id=456]

I want to check if my List has a string. For example, if it contains name or id? When I use the contains method, it returns false. Clearly I am doing something wrong. How do I check if a list of objects has a string?

5
  • You need to override the equals and hashcode methods of MyObj. Commented Sep 18, 2014 at 18:22
  • 2
    I'm confused... Can you simplify your question? Commented Sep 18, 2014 at 18:22
  • If you already iterate through the list you hadn't the idea of using entity.getName().equals(searchString) and entity.getId().equals(searchId)? Commented Sep 18, 2014 at 18:29
  • I am not doing a equality check on the values (test 123, testOne,456), but rather on the fields name and id Commented Sep 18, 2014 at 18:35
  • @rickygrimes Isn't this what I wrote? Check the fields instead of using list.contains(). Commented Sep 18, 2014 at 18:43

2 Answers 2

1

You might want something like Java8 Stream and filter, but if I understand your question (and the answers and comments) you want to get all the MyObj matching a criteria?

In that case, equals is not the way to do it. eg:

MyObj a = ...
a.setName("A");
a.equals("A"); // returns true
"A".equals(a); // returns false!

The javadoc of equals says that:

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. For any non-null reference value x, x.equals(null) should return false.

And in that case, you have a non symmetric equals (even if javadocs says it should be rather than it must be).

You can use filter, or better Java 8's Stream.

In pre Java 8, for loops, or external library such as Guava is the way to go.

The "simple" use case is the following:

List<MyObj> matching = new ArrayList<>();
for (MyObj o : list) {
  if (null != o.getName() || null != o.getId()) {
    matching.add(o);
  }
}

This says that you have either a name defined (eg: not null), either an id.

If you need to go further, with advanced criteria, you can do that:

interface Predicate<T> {
  boolean test(@Nullable T value);
}

public class Lists {
static <T> List<T> filter(List<? extends T> list, Predicate<T> predicate) {
  List<MyObj> matching = new ArrayList<>();
  for (MyObj o : list) {      
    if (predicate.test(o)) {
      matching.add(o);
    }
  }
  return matching;
}
}

And an example:

Lists.filter(listMyObj, new Predicate<MyObj>() {
  public boolean test(MyObj o) {
    return null != o.getName() || null != o.getId();
  }
});

But you should use Guava since it does the same, and better (my example is more or less what Guava does).

As for Java 8:

myList.stream()
      .filter(o -> null != o.getName() || null != o.getId())
      .collect(Collectors.toList())

And I think you can do better using MyObj::getName/getId and some Function wrapper, to do the "isNull" test.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to implement equals method in your MyObj

4 Comments

If its not implemented, can I not do it?
He wants to look for ids or names so equals won't really solve the problem
@rickygrimes it's not implemented obviously. YOU need to do it :)
That's not was equals is for. And read the Javadoc: docs.oracle.com/javase/7/docs/api/java/lang/… : It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.