I have a use case for filtering a set of objects based on multiple properties of the object. An approach that I would use in Javascript might be to create an object with only the properties that I care about, then check those property names against the objects I wish to filter.
Example (in Typescript):
example(): void {
let template = {
name: 'Test',
color: 'Blue'
};
let objects = [
{ name: 'Test', color: 'Blue' },
{ name: 'Test2', color: 'Blue' },
{ name: 'Test', color: 'Red' },
{ name: 'Test', color: 'Blue', extra: true },
];
let results = objects.map(o => this.compare(o, template));
console.log(results);
}
compare(obj, template): boolean {
for (const prop in template) {
if (obj[prop] !== template[prop]) {
return false;
}
}
return true;
}
The above will write [true, false, false, true]
to the console. The reason this is cool is that it will accept basically any object and issue the correct results. It's not obvious to me how to provide this feature in Java, such that I could avoid having to implement a comparison function on hundreds of data model beans.
Is there a built-in or commonly-used way to do the equivalent comparison in Java in a generic manner?