I'm trying to figure out if there is an elegant way of doing the following using Java streams:
So far the only way I've been able to do it is to create an intermediate map at each level, which works but feels very dirty. Is there an accepted way to do this, eg by implementing a custom Collector or something like that?
Just create a Comparator<Pojo>:
Comparator<Pojo> comparator =
    Comparator.comparingInt(
        p -> StringUtils.getLevenshteinDistance(p.surname(), surnameTypedIn)
Then use the Stream.min method:
Optional<Pojo> minPojo = listOfPojos.stream().min(comparator);
(You can inline the Comparator.comparingInt in the Stream.min call if you want; I just separated them for readability).
Or, without streams:
Pojo minPojo = Collections.min(listOfPojos, comparator);
Note that this way will throw a NoSuchElementException if listOfPojos is empty.
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