简体   繁体   English

检查自定义列表是否包含项目

[英]Check if custom List contains an Item

I've got an custom List and want to check if it contains a special Item. 我有一个自定义列表,想检查它是否包含特殊项目。 TheList is populated with Rowlayout objects. TheList中填充了Rowlayout对象。

public RowLayout(String content, int number) {
        this.content = content;
        this.number = number;
    }

Now i wanna check if my List<Roalayout> contains a special item at the content - position. 现在我想检查我的List<Roalayout>是否在content -位置上包含特殊项目。 How do I do that? 我怎么做?

It doesn't work with just asking .contains' . 仅询问.contains'并不起作用。

What i wanna check: 我想检查的是:

if (!List<RowLayout>.contains("insert here"){
//Do something
}

If you can edit the class RowLayout just override hashCode and equals with whatever equality you want for them. 如果您可以编辑类RowLayout只需重写hashCodeequals您想要的相等性即可。

If you can't and have java-8 for example, this could be done: 如果不能,例如使用java-8,则可以这样做:

String content = ...
int number = ...

boolean isContained = yourList.stream()
        .filter(x -> x.getContent().equals(content))   
        .filter(x -> x.getNumber() == number)
        .findAny()
        .isPresent();

You can obviously return the instance you are interested in from that Optional from findAny . 很明显,您可以从findAny Optional返回您感兴趣的实例。

You just need to override equals for List.contains to work accordingly. 您只需要重写equals List.contains可以正常工作。 List.contains says in the documentation: List.contains在文档中说:

Returns true if and only if this list contains at least one element e such that 当且仅当此列表包含至少一个元素e时返回true
(o==null ? e==null : o.equals(e) ). (o == null?e == null: o.equals(e) )。

Your implementation of equals may look like this: 您的equals实现可能如下所示:

class RowLayout {
    private String content;
    private int number;

    public boolean equals(Object o)
    {
        if (!(o instanceof RowLayout)) return false;
        final RowLayout that = (RowLayout) o;
        return this.content.equals(that.content) && this.number == that.number;
    }
}

Don't forget to also override hashCode , else your class will not work in hash-based structures like HashSet s or HashMap s. 不要忘记也重写hashCode ,否则您的类将无法在基于哈希的结构(如HashSetHashMap

Example usage: 用法示例:

myList.contains(new RowLayout("Hello", 99));

An alternative Java 8 solution if you only care about the content and don't care about the number would be to do this: 如果您只关心内容而不关心数量,那么另一个Java 8解决方案是:

boolean isContained = myList.stream() 
                            .map(RowLayout::getContent)
                            .anyMatch("some content");

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

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