How to get multiple values from an object using a single stream operation?

前端 未结 5 1297
梦如初夏
梦如初夏 2020-12-10 05:45

I want to determine the minimum area required to display a collection of points. The easy way is to loop through the collection like this:

int minX = Integer         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 06:24

    You are able to use 2 Streams using Stream::reduce to get a point with a minimum and a point with a maximum. I don't recommend to concatenate the results to a one stream since there might be hard to distinguish the difference between the minimum, maximum and the coordinates.

    Point min = points
        .stream()
        .reduce((l, r) -> new Point(Math.min(l.y, r.y), Math.min(l.y, r.y))
        .orElse(new Point(-1, -1));
    
    Point max = points
        .stream()
        .reduce((l, r) -> new Point(Math.max(l.y, r.y), Math.max(l.y, r.y))
        .orElse(new Point(-1, -1));
    

    As the BinaryOperator use the two subsequent Points and a ternary operator to find out the minimum/maximum which is passed to a new object Point and returned using Optional::orElse with the default -1, -1 coordinates.

提交回复
热议问题