Averaging across multiple fields with IntSummaryStatistics

前端 未结 2 658
无人共我
无人共我 2021-01-07 01:07

I\'m trying to use Java 8 streams to create a single CarData object, which consists of an average of all the CarData fields in the list coming from getCars;

2条回答
  •  滥情空心
    2021-01-07 01:29

    You need to write your own Collector, something like this:

    class CarDataAverage {
        public static Collector> get() {
            return Collector.of(CarDataAverage::new, CarDataAverage::add,
                                CarDataAverage::combine,CarDataAverage::finish);
        }
        private long sumBodyWeight;
        private long sumShellWeight;
        private int count;
        private void add(CarData carData) {
            this.sumBodyWeight += carData.getBodyWeight();
            this.sumShellWeight += carData.getShellWeight();
            this.count++;
        }
        private CarDataAverage combine(CarDataAverage that) {
            this.sumBodyWeight += that.sumBodyWeight;
            this.sumShellWeight += that.sumShellWeight;
            this.count += that.count;
            return this;
        }
        private Optional finish() {
            if (this.count == 0)
                return Optional.empty();
            // adjust as needed if averages should be rounded
            return Optional.of(new CarData((int) (this.sumBodyWeight / this.count),
                                           (int) (this.sumShellWeight / this.count)));
        }
    }
    

    You then use it like this:

    List list = ...
    
    Optional averageCarData = list.stream().collect(CarDataAverage.get());
    

提交回复
热议问题