Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract only one allowed element from a stream?

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?

like image 930
membersound Avatar asked May 25 '20 12:05

membersound


People also ask

How do you get a single element from a stream?

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.

How to get last element from stream?

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.


1 Answers

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();
like image 94
Eklavya Avatar answered Sep 19 '22 14:09

Eklavya