java 检查 List<Object> 是否包含属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33260177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:26:25  来源:igfitidea点击:

Check if a List<Object> contains a property

javalistcontains

提问by user_mda

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. Is there an API available to achieve this in Java?

我想检查这个列表是否包含“name2”,而不必遍历列表。是否有可用于在 Java 中实现此目的的 API?

回答by JB Nizet

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

回答by Thanigai Arasu

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

您可以HashMap<String,MyObject>在这种情况下使用。

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

如果要根据名称进行检查。然后在HashMap中使用name作为key。

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
}

回答by Leonid Vorozhun

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

如果 MyObject 是您自己的类,您可以适当地覆盖方法 equals(和哈希码)。因此,您可以使用标准方法 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. :)

附注。但实际上无论如何都会有某种依赖于 List 实现的循环。他们中的一些人可能会进行简单的迭代。:)