My requirement is to filter a list of objects by a string matching any of the properties.
For example, let say Contact class has three properties: street, city, phone.
I am aware of how java stream filter works, where i have to compare the input string with each property as below:
contactList.stream().filter(contact -> contact.getStreet().equals("dubai") ||
contact.getCity().equals("dubai") || .......).collect(Collectors.toList());
However, if a class has 20+ properties and size of list 80,000+, comparing each property with the input string would affect the performance. So my question is, does Java or any other library support filtering the list with any matching property? Something as below:
contactList.stream().filter(contact -> contact.anyProperty.equals("dubai").collect(Collectors.toList());
Can someone help me on this, thanks.
You can use findAny. This will end as soon as the candidate is found:
Optional<Contact> contact = contactList.stream().filter(contact -> contact.getStreet().equals("dubai") ||
contact.getCity().equals("dubai") || .......).findAny();
Or if you only need an information if such an object exists, use anyMatch:
boolean exists = contactList.stream().anyMatch(contact -> contact.getStreet().equals("dubai") ||
contact.getCity().equals("dubai") || .......);
You can solve this by using reflection to read all class properties
or
By overriding toString() method and check if the result of to String contains input string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With