2016-08-07 46 views
2
class Stock{ 
    double profit; 
    double profitPercentage; 
    public double getProfit(){ 
     return profit; 
    } 
    public double getProfitPercentage(){ 
     return profitPercentage; 
    } 
} 
List<Stock> stocks = getAllStocks(); 
stocks.stream.collect(Collectors.summarizingDouble(Stock:getProfit)).getSum(); 
stocks.stream.collect(Collectors.summarizingDouble(Stock:getProfitPercentage)).getSum(); 

我無法找到單向傳輸流的方法。任何幫助或指針都會很好。如何從Java中的流中收集兩筆總和8

+1

您正在尋找[像這樣](http://stackoverflow.com/a/30211021/1743880)。 – Tunaki

+0

鏈接顯示類似groupby和sum的內容。對我而言,我需要執行2個字段的總和,而不是通過組。 –

+0

你是所有利潤和利潤百分比的總和嗎? –

回答

1

直接的方法是創建一個自定義收藏夾類。

public class StockStatistics { 

    private DoubleSummaryStatistics profitStat = new DoubleSummaryStatistics(); 
    private DoubleSummaryStatistics profitPercentageStat = new DoubleSummaryStatistics(); 

    public void accept(Stock stock) { 
     profitStat.accept(stock.getProfit()); 
     profitPercentageStat.accept(stock.getProfitPercentage()); 
    } 

    public StockStatistics combine(StockStatistics other) { 
     profitStat.combine(other.profitStat); 
     profitPercentageStat.combine(other.profitPercentageStat); 
     return this; 
    } 

    public static Collector<Stock, ?, StockStatistics> collector() { 
     return Collector.of(StockStatistics::new, StockStatistics::accept, StockStatistics::combine); 
    } 

    public DoubleSummaryStatistics getProfitStat() { 
     return profitStat; 
    } 

    public DoubleSummaryStatistics getProfitPercentageStat() { 
     return profitPercentageStat; 
    } 

} 

本課程作爲兩個DoubleSummaryStatistics的包裝。每當一個元素被接受時,它就代表它們。就你而言,由於你只對這筆款項感興趣,你甚至可以使用Collectors.summingDouble而不是DoubleSummaryStatistics。此外,它返回兩個統計數據getProfitStatgetProfitPercentageStat;或者,您可以添加一個修整機操作,該操作將返回僅包含兩個總和的double[]

然後,您可以使用

StockStatistics stats = stocks.stream().collect(StockStatistics.collector()); 
System.out.println(stats.getProfitStat().getSum()); 
System.out.println(stats.getProfitPercentageStat().getSum()); 

一個更通用的方法是創建能夠配對其他收藏家的收藏家。您可以使用pairing收集器編寫in this answer,也可用in the StreamEx library

double[] sums = stocks.stream().collect(MoreCollectors.pairing(
    Collectors.summingDouble(Stock::getProfit), 
    Collectors.summingDouble(Stock::getProfitPercentage), 
    (sum1, sum2) -> new double[] { sum1, sum2 } 
)); 

利潤的總和將是sums[0]和利潤百分比的總和將在sums[1]。在這個片段中,只有數據被保留,而不是整個數據。