简体   繁体   English

检查清单 <Object> 包含一个属性

[英]Check if a List<Object> contains a property

I have the following list in java 我在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. 我想检查此列表是否包含“ name2”,而不必遍历该列表。 Is there an API available to achieve this in Java? 是否有可用的API在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: 最简单的方法是使用Java 8流:

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

You can use HashMap<String,MyObject> in this case. 在这种情况下HashMap<String,MyObject>可以使用HashMap<String,MyObject>

If you want to check based on the name. 如果要根据名称进行检查。 Then use name as the key in HashMap. 然后使用name作为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. 如果MyObject是您自己的类,则可以适当地重写equals(和哈希码)方法。 As a result you could use standard method list.contains 因此,您可以使用标准方法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. PS。 But actually there will be anyway some kind of loop which depends on List implementation. 但是实际上,总会有某种依赖于List实现的循环。 Some of them might do plain iteration. 其中一些可能会进行简单的迭代。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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