這段代碼背后的想法是,它從三個.csv按年份組織的帶有鍵的檔案中讀取資料,并按年份檢索資料的總和,以及每年的最小和最大數量。
問題是,列印時它按降序回傳年度結果。
我需要幫助找出一種反轉流的方法,以便每個檔案的年度資料按升序排列。
public class SalesGenerator {
//This class will print out the Maximum and minimum Sales data from the .getSales() in TeslaImport.
public static void teslaReport(
Set<Entry<String, List<TeslaImport>>> entrySet,
List<TeslaImport> teslaModel, String modelName)
throws IOException {
//This comparator will sort the sales array values.
Comparator<TeslaImport> comparativeOperator = Comparator.comparing(tesla -> tesla.getSales());
entrySet.stream().forEach(entry -> System.out.println(
"Month: " entry.getKey() " -> "
entry.getValue().stream()
.mapToInt(tesla -> tesla.getSales().intValue())
.sum()
));
TeslaImport maximumSales = teslaModel.stream()
.max(comparativeOperator)
.orElseThrow(NoSuchElementException::new);
TeslaImport minimumSales = teslaModel.stream()
.min(comparativeOperator)
.orElseThrow(NoSuchElementException::new);
//Print out the maximum and minimum results from TeslaReport.
System.out.println(modelName " Yearly Sales Report");
System.out.println("The BEST month for " modelName " was: " maximumSales.getDate());
System.out.println("The WORST month for " modelName " was: " minimumSales.getDate());
}
public static void main(String[] args) throws IOException {
/* To produce the sales values from TeslaData, we need to instantiate the TeslaData variable to import
all the EntrySet models */
TeslaData analysedData = new TeslaData();
/*The FileReader from our FileGenerator class needs to be instantiated to model3. We can use to when
when reporting our data in TeslaReport */
List<TeslaImport> model3 = FileGenerator.teslaFileRead("model3.csv");
Set<Entry<String, List<TeslaImport>>> entrySetModel3 = analysedData.entryByYear(model3);
teslaReport(entrySetModel3, model3, "Model 3");
/*The FileReader from our FileGenerator class needs to be instantiated to modelS. We can use to when
when reporting our data in TeslaReport */
List<TeslaImport> modelS = FileGenerator.teslaFileRead("modelS.csv");
Set<Entry<String, List<TeslaImport>>> entrySetModelS = analysedData.entryByYear(modelS);
teslaReport(entrySetModelS, modelS, "Model S");
/*The FileReader from our FileGenerator class needs to be instantiated to modelX. We can use to when
when reporting our data in TeslaReport */
List<TeslaImport> modelX = FileGenerator.teslaFileRead("modelX.csv");
Set<Entry<String, List<TeslaImport>>> entrySetModelX = analysedData.entryByYear(modelX);
teslaReport(entrySetModelX, modelX, "Model X");
}
}
注: TeslaImport在這里我把我的班JavaBean中的(get/set,toString,date和sales)
uj5u.com熱心網友回復:
entryByYear由于為從類中的方法檢索的條目集列印報告資料TeslaModel,因此該方法很可能回傳按降序排序的樹形圖的條目集。因此,要更改順序,應按鍵重新排序流:
entrySet.stream()
.sorted(Map.Entry.comparingByKey())
.forEach(entry -> System.out.println(
"Month: " entry.getKey() " -> "
entry.getValue().stream()
.mapToInt(tesla -> tesla.getSales().intValue())
.sum()
));
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/421041.html
標籤:
