0

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
}
Sarius
  • 35
  • 7

2 Answers2

7

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.

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Sorry, but im a total beginner. What do you mean by "just override `hashCode` and `equals`"? – Sarius Aug 10 '17 at 09:04
  • @Sarius https://www.google.com/search?q=java+override+hashcode+and+equals&rlz=1C5CHFA_enMD720MD720&oq=java+override+hashcode+&aqs=chrome.5.69i57j69i60j0l4.6046j0j7&sourceid=chrome&ie=UTF-8 – Eugene Aug 10 '17 at 09:05
2

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");
Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
Michael
  • 41,989
  • 11
  • 82
  • 128