Reputation: 35
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
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 HashSet
s or HashMap
s.
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
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