I have a list of elements, and want to extract the value of the fields' propery. Problem: all elements should have the same property value.
Can I do better or more elegant than the following?
Set<String> matches = fields.stream().map(f -> f.getField()).collect(Collectors.toSet());
if (matches.size() != 1) throw new IllegalArgumentException("could not match one exact element");
String distrinctVal = matches.iterator().next(); //continue to use the value
Is this possible directly using the stream methods, eg using reduce
?
To find an element matching specific criteria in a given list, we: invoke stream() on the list. call the filter() method with a proper Predicate. call the findAny() construct, which returns the first element that matches the filter predicate wrapped in an Optional if such an element exists.
The other way to get the last element of the stream is by skipping all the elements before it. This can be achieved using Skip function of Stream class. Keep in mind that in this case, we are consuming the Stream twice so there is some clear performance impact.
Your current solution is good. You can try this way also to avoid collecting.
Use distinct()
then count()
if (fields.stream().map(f -> f.getField()).distinct().count() != 1)
throw new IllegalArgumentException("could not match one exact element");
To get the value
String distrinctVal = fields.get(0).getField();
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