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 expect
Well, i think your approach is a bit overcomplicating the problem. You said:
I have a list of DTO received from a DB, and they have an ID.
Then probably you should use a DTO class to hold those items. If so put id getter and setter inside that class:
public class DTO implements HasId{
void setId(Long id);
Long getId();
}
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:
public boolean containsId(List<HasId> list, long id) {
for (HasId object : list) {
if (object.getId() == id) {
return true;
}
}
return false;
}
public boolean containsId(List<HasId> list, long id) {
boolean flag = false;
for (HasId object : list) {
if (object.getId() == id) {
flag = true;
}
}
return flag;
}
This is what I used in my DFS GetUnvisitedNeighbour function.
public static int GetUnvisitedNeighbour(int v)
{
Vertex vertex = VertexList.stream().filter(c -> c.Data == v).findFirst().get();
int position = VertexList.indexOf(vertex);
...
}
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()
or findAny.get()
according to your logic.
I propose to create simple static method like you wrote, without any additional interfaces:
public static boolean containsId(List<DTO> list, long id) {
for (DTO object : list) {
if (object.getId() == id) {
return true;
}
}
return false;
}
I suggest you just override the equals
in your SearchableDto
it would be something like:
public boolean equals(Object o){
if (o instanceof SearchableDto){
SearchableDto temp = (SearchableDto)o;
if (this.id.equals(temp.getId()))
return true;
}
return false;
}
In this case contains
should work probably if it has the same id
;
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:
SELECT * FROM employee WHERE firstname = 'John' OR id = 42;