简体   繁体   中英

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?

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()));

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
}

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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM