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

前端 未结 5 1300
梦如初夏
梦如初夏 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:38

    You could divide by two the iterations with summaryStatistics() while keeping a straight code :

    IntSummaryStatistics stat = points.stream().mapToInt(point -> point.x).summaryStatistics();
    int minX = stat.getMin();
    int maxX = stat.getMax();
    

    And do the same thing with point.y.
    You could factor out in this way :

    Function, IntSummaryStatistics> statFunction =
            intExtractor -> points.stream()
                                  .mapToInt(p -> intExtractor.applyAsInt(pp))
                                  .summaryStatistics();
    
    IntSummaryStatistics statX = statFunction.apply(p -> p.x);
    IntSummaryStatistics statY = statFunction.apply(p -> p.y);
    

    A custom collector is a possibility but note that you should implement the combiner part that will make your code harder to read.
    So but if you need to use parallel stream you should stay to the imperative way.
    While you could improve your actual code by relying the Math.min and Math.max functions :

    for (Point p : points) {
        minX = Math.min(p.x, minX);
        minY = Math.min(p.y, minY);
        maxY = Math.max(p.x, maxX);
        maxY = Math.max(p.y, maxY);
    }
    

提交回复
热议问题