Eugene Shevchugov
Eugene Shevchugov

Reputation: 77

Union Streams in Java

I think this question is useless, but i can`t find how i can union this code to one line

I have List of active Couriers. I am trying to find all free couriers in this list and after that find courier with min distance

List<Courier> afterCheckIsFree = activeCouriers.stream().filter(Courier::isFree).collect(Collectors.toList());
final Optional<Courier> courierWithMinDistance = afterCheckIsFree.stream()
                .filter(n -> n.getId().equals(CourierFinder.minDistanceUsingCourier(Point.ZERO_POINT, afterCheckIsFree).getId())).findFirst();

Thanks a lot!

Upvotes: -2

Views: 116

Answers (3)

Bohemian
Bohemian

Reputation: 424993

Change the minDistanceUsingCourier method to return the distance for a single courier (instead of the minimum distance of a list of couriers) then:

final Optional<Courier> courierWithMinDistance = activeCouriers.stream()
  .filter(Courier::isFree)
  .min(comparing(c -> minDistanceUsingCourier(Point.ZERO_POINT, c)));

Upvotes: 1

rzwitserloot
rzwitserloot

Reputation: 102852

Assuming that the actual aim is to find the courier that is both free and has the minimum distance...

Your code will run the minDistance algorithm for every courier, so it is incredibly inefficient. It can be done in one go:

Optional<Courier> = activeCouriers.stream()
  .filter(Courier::isFree)
  .min((c1, c2) -> c1.getDistanceFrom(ZERO_POINT) - c2.getDistanceFrom(ZERO_POINT));

min can find the minimum thing in the stream based on whatever function you want, which is what is used here.

Upvotes: 0

stinger
stinger

Reputation: 4138

You should apply 2 criterias on your stream: firstly, checking if courier is free, secondly, sort remaining couriers by distance and take first. It will look like:

list.stream().filter(Courier::isFree).sorted((c1, c2)->c1.getDistance().
                               compareTo(c2.getDistance())).
                               findFirst();

Upvotes: 0

Related Questions