简体   繁体   English

在 Java8 中使用流重写

[英]Rewriting using streams in Java8

I need some help with how I would rewrite this code using streams in Java.我需要一些关于如何使用 Java 中的流重写此代码的帮助。 I am new to coding and could use some assistance.我是编码新手,可以使用一些帮助。 Thank you for your time.感谢您的时间。 I have this class called thisDoesStuff that uses the doControlMethod.我有一个名为 thisDoesStuff 的 class,它使用 doControlMethod。

 public void thisDoesStuff() {
        MealType previousMealType = null;
        int count = 0;
        int total = 0;
        int min = 0;
        int max = 0;
        int median = 0;
        double mean = 0;
        int index;
        for (int i = 0; i < mealList.size(); i++) {
            if (mealList.get(i) != null) {
                previousMealType = mealList.get(i).getMealType();
                if (mealList.get(i).getMealType() != previousMealType && previousMealType != null) {
                    System.out.printf("%-9s %9s %9s %9s %9s %9s \n", previousMealType.getPrettyPrint(), total,
                            String.format("%" +
                                    ".2f",
                            mean), min, max, median);
                }
                min = mealList.get(i).getCalories();
                count++;
                total += mealList.get(i).getCalories();
                mean = (double) total / count;
                if (max < mealList.get(i).getCalories()) {
                    max = mealList.get(i).getCalories();
                }
                index = count / 2;
                median = mealList.get(index).getCalories();

            }
            System.out.printf("%-9s %9s %9s %9s %9s %9s \n", previousMealType.getPrettyPrint(), total, String.format(
                    "%.2f",
                    mean), min,
                    max, median);
        }


    }

I am going to simply show you how to iterate without forloop.我将简单地向您展示如何在没有 forloop 的情况下进行迭代。 The logic you have inside your if statement is wrong.您在 if 语句中的逻辑是错误的。

   previousMealType = mealList.get(i).getMealType();
                if (mealList.get(i).getMealType() != previousMealType && previousMealType != null) {
                    System.out.printf("%-9s %9s %9s %9s %9s %9s \n", previousMealType.getPrettyPrint(), total,
                            String.format("%" +
                                    ".2f",
                            mean), min, max, median);
                }

How is this working for you exactly?这对你有什么作用? previousMealType will always be replaced to equal mealList.get(i)......... previousMealType 将始终被替换为等于 mealList.get(i)............

I will just give you pointers...I will not rewrite it, as it feels like homework.我只会给你指点......我不会重写它,因为它感觉像家庭作业。

MealType previousMealType = null;

mealList.forEach(currentElement -> {

     
      //Logic goes here...
      if(currentElement != null){

            //Do something
         if(previousMealType != null && currentElement.getMealType() != previousMealType){

         }
         //Now set this, not first thing....
         previousMealType = currentElement.getMealType();
       }
 });
 

or或者

 mealList.stream().forEach(currentElement -> {
     
      //Logic goes here...
      if(currentElement != null){

            //Do something
         if(previousMealType != null && currentElement.getMealType() != previousMealType){

         }
         //Now set this, not first thing....
         previousMealType = currentElement.getMealType();
       }
     
 });

The elements in a list when using stream() are meant to be consumed one after the other, and not to do list.get(index);使用 stream() 时列表中的元素意味着一个接一个地被消耗,而不是执行 list.get(index);

Well first of all, you seem to want to do this by meal type, so那么首先,你似乎想按餐食类型来做这个,所以

Map<MealType, List<Meal>> byType = meals.stream().groupingBy(Meal::getType);

For (most) of the things you're calculating, there's actually a class IntSummaryStatistics , so what you can do is对于(大多数)你正在计算的东西,实际上有一个 class IntSummaryStatistics ,所以你可以做的是

for (List<Meal> fromSingleType : byType.getValueSet()) {
  IntSummaryStatistics stats = fromSingleType.stream()
    .mapToInt(Meal::getCalories)
    .collect(Collectors.summarizingInt());
  // stats has count, average, min, max. Missing the median though.
}

Median calculation is not done easily with streams, if at all, since you're always handling a single item at the time, so you don't known when you're "in the middle" of the value set.使用流计算中值并不容易,如果有的话,因为您当时总是处理一个项目,所以您不知道何时处于值集的“中间”。 Best thing you can do is create a sorted list of all calory values and take caloryList.get(caloryList.size()/2) .您可以做的最好的事情是创建一个所有卡路里值的排序列表并使用caloryList.get(caloryList.size()/2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM