user_mda
user_mda

Reputation: 19388

Check if a List<Object> contains a property

I have the following list in java

List<MyObject> =[id ="id", name= "name", time =DateObj, id = "id2", name = "name2".. ]

I want to check if this list contains "name2" without having to loop through the list. Is there an API available to achieve this in Java?

Upvotes: 1

Views: 26143

Answers (3)

Leonid Vorozhun
Leonid Vorozhun

Reputation: 1

If MyObject is your own class you can override methods equals (and hashcode) appropriately. As a result you could use standard method list.contains

List<MyObject> myObjectList = ...;
...
MyObject objectToBeFound = new MyObject("name2", ...);
if (myObjectList.contains(objectToBeFound))
{
    //object is in the list
}
else
{
    //it is not in the list
}

PS. But actually there will be anyway some kind of loop which depends on List implementation. Some of them might do plain iteration. :)

Upvotes: 0

Thanigai Arasu
Thanigai Arasu

Reputation: 413

You can use HashMap<String,MyObject> in this case.

If you want to check based on the name. Then use name as the key in HashMap.

HashMap<String, MyObject> map = new HashMap<String, MyObject>();
map.put(obj.getName(), obj);

To check the map contains the particular value.

if (map.containsKey("name2")) {
     // do something
}

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691755

There is no way to do that without looping. But of course, the loop can be done by a library method instead of being done by you.

The simplest way to do that is to use Java 8 streams:

boolean name2Exists = list.stream().anyMatch(item -> "name2".equals(item.getName()));

Upvotes: 30

Related Questions