【发布时间】:2022-01-22 17:17:44
【问题描述】:
这段代码背后的想法是,它从三个.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)
【问题讨论】:
标签: java eclipse java-stream