Java List.contains(字段值等于x的对象) [英] Java List.contains(Object with field value equal to x)

查看:29
本文介绍了Java List.contains(字段值等于x的对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查 List 是否包含一个具有特定值字段的对象.现在,我可以使用循环来进行检查,但我很好奇是否有更高效的代码.

I want to check whether a List contains an object that has a field with a certain value. Now, I could use a loop to go through and check, but I was curious if there was anything more code efficient.

类似的东西;

if(list.contains(new Object().setName("John"))){
    //Do some stuff
}

我知道上面的代码并没有做任何事情,它只是粗略地展示了我想要实现的目标.

I know the above code doesn't do anything, it's just to demonstrate roughly what I am trying to achieve.

另外,为了澄清一下,我不想使用简单循环的原因是因为这段代码当前将进入一个循环内的循环内,而该循环内在一个循环内.为了可读性,我不想继续向这些循环添加循环.所以我想知道是否有任何简单的(ish)替代方案.

Also, just to clarify, the reason I don't want to use a simple loop is because this code will currently go inside a loop that is inside a loop which is inside a loop. For readability I don't want to keep adding loops to these loops. So I wondered if there were any simple(ish) alternatives.

推荐答案

Streams

如果您使用的是 Java 8,也许您可​​以尝试这样的操作:

Streams

If you are using Java 8, perhaps you could try something like this:

public boolean containsName(final List<MyObject> list, final String name){
    return list.stream().filter(o -> o.getName().equals(name)).findFirst().isPresent();
}

或者,您可以尝试这样的操作:

Or alternatively, you could try something like this:

public boolean containsName(final List<MyObject> list, final String name){
    return list.stream().map(MyObject::getName).filter(name::equals).findFirst().isPresent();
}

如果List 包含名称为nameMyObject,则此方法将返回true.如果您想对 getName().equals(name) 的每个 MyObject 执行操作,那么您可以尝试这样的操作:

This method will return true if the List<MyObject> contains a MyObject with the name name. If you want to perform an operation on each of the MyObjects that getName().equals(name), then you could try something like this:

public void perform(final List<MyObject> list, final String name){
    list.stream().filter(o -> o.getName().equals(name)).forEach(
            o -> {
                //...
            }
    );
}

其中 o 代表一个 MyObject 实例.

Where o represents a MyObject instance.

或者,正如评论所建议的(感谢 MK10),您可以使用 Stream#anyMatch 方法:

Alternatively, as the comments suggest (Thanks MK10), you could use the Stream#anyMatch method:

public boolean containsName(final List<MyObject> list, final String name){
    return list.stream().anyMatch(o -> o.getName().equals(name));
}

这篇关于Java List.contains(字段值等于x的对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆