Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA 8 filter list of object with any matching property

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.

like image 720
Mujahid Avatar asked Oct 23 '25 14:10

Mujahid


2 Answers

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") || .......);
like image 74
Andronicus Avatar answered Oct 26 '25 06:10

Andronicus


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

like image 24
AMA Avatar answered Oct 26 '25 04:10

AMA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!