I have a list of DTO received from a DB, and they have an ID. I want to ensure that my list contains an object with a specified ID. Apparently creating an object with expected fields in this case won't help because contains() calls for Object.equals(), and they won't be equal.
I came up to a solution like so: created an interface HasId
, implemented it in all my DTOs, and inherited ArrayList with a new class that has contains(Long id)
method.
public interface HasId {
void setId(Long id);
Long getId();
}
public class SearchableList<T extends HasId> extends ArrayList<T> {
public boolean contains(Long id) {
for (T o : this) {
if (o.getId() == id)
return true;
}
return false;
}
}
But in this case I can't typecast List and ArrayList to SearchableList... I'd live with that, but wanted to make sure that I'm not inventing the bicycle.
EDIT (Oct '16):
Of course, with the introduction of lambdas in Java 8 the way to do this is straightforward:
list.stream().anyMatch(dto -> dto.getId() == id);
I suggest you just override the
equals
in yourSearchableDto
it would be something like:In this case
contains
should work probably if it has the sameid
;I propose to create simple static method like you wrote, without any additional interfaces:
You requirement is not clear to me. When you say 'ensure that my list contains an object with a specified ID' do you want to:
Most responses have assumed you mean 1, however when thinking about it you could just as well mean 2 given the wording of the question. You could include the required result by altering your query:
Well, i think your approach is a bit overcomplicating the problem. You said:
Then probably you should use a DTO class to hold those items. If so put id getter and setter inside that class:
That's enough for iterate through and ArrayList and search for the desired id. Extending ArrayList class only for adding the "compare-id" feautre seems overcomplicated o me. @Nikita Beloglazov make a good example. You can generalize it even more:
This is what I used in my DFS GetUnvisitedNeighbour function.
I used to work in C#. Lambda expressions in C# are much easier to work with than they are in Java.
You can use
filter
function to add condition for property of element.Then use
findFirst().get()
orfindAny.get()
according to your logic.