Reputation: 2516
I am trying to get a filtered object through a stream api.
I have a list of VendorAddress , where a single address is a primary address. Here I am trying to filter that address and want it to return a VendorAddress object.
See below code:
vendorAddressList.stream().filter(vendorAddressObj-> vendorAddressObj.isPrimary())
What should I do to get the filtered VendorAddress object.
Thanks in advance.
Upvotes: 1
Views: 76
Reputation: 20618
Use the findAny
terminal method:
Optional<VendorAddress> maybeAnAddress = vendorAddressList
.stream()
.filter(VendorAddress::isPrimary) // Note: I used a method reference here.
.findAny();
VendorAddress primaryAddress = maybeAnAddress.orElse(null);
Upvotes: 3
Reputation: 1885
There are dozen ways to achieve that you want. For instance, you can grab first matched element like this
Optional<VendorAddress> result = vendorAddressList.stream()
.filter(vendorAddressObj-> vendorAddressObj.isPrimary()).findFirst();
or any matched
Optional<VendorAddress> result = vendorAddressList.stream()
.filter(vendorAddressObj-> vendorAddressObj.isPrimary()).findAny();
In case if you're want all matched elements
List<VendorAddress> result = vendorAddressList.stream()
.filter(vendorAddressObj-> vendorAddressObj.isPrimary()).collect(Collectors.toList());
and many more... Hope it helps!
Upvotes: 2
Reputation: 526
You can use findFirst and either get (if you want an exception when not found) or orElse(null) (if you want null when not found).
Like this
VendorAddress address = vendorAddressList.stream()
.filter(vendorAddressObj-> vendorAddressObj.isPrimary())
.findFirst() //Can be changed to findAny()
.orElse(null); //Can be changed to get()
This will return the first found instance in your list. If you are sure you only have one, or does not care that it strictly returns the same (first) element every time, you can use findAny() instead of findFirst() for better performance.
Upvotes: 1