Sarius
Sarius

Reputation: 35

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.

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. How do I do that?

It doesn't work with just asking .contains'.

What i wanna check:

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

Upvotes: 0

Views: 1437

Answers (2)

Michael
Michael

Reputation: 44150

You just need to override equals for List.contains to work accordingly. List.contains says in the documentation:

Returns true if and only if this list contains at least one element e such that
(o==null ? e==null : o.equals(e)).

Your implementation of equals may look like this:

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 HashSets or HashMaps.

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:

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

Upvotes: 2

Eugene
Eugene

Reputation: 120858

If you can edit the class RowLayout just override hashCode and equals with whatever equality you want for them.

If you can't and have java-8 for example, this could be done:

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.

Upvotes: 7

Related Questions