使用Java Stream API计算中位数

乔·H

是否可以使用Java Stream API查找数字集合的中位数?我有一个List<Double>未排序的类型的变量

从JDK9到14的javadocs似乎表明这median()不是的有效方法DoubleStream平均值,最小值,最大值,计数和总和是有效的聚合函数。

median()不是有效方法,因为它需要在流传输之前进行排序的Collection?

这适用于average()

   // Function to find average element from a List of Integers in Java 9 and above
   public static Double getAverageWithStream(List<Double> list) {
      OptionalDouble average = list.stream() // Stream<Double>
                                 .mapToDouble(v -> v) // DoubleStream
                                 .average(); // OptionalDouble

      // Print out a message about the 'average' variable's value
      // Note: ifPresentOrElse() was introduced in JDK9
      average.ifPresentOrElse(
         // message the value if one exists
         (value) -> {
            System.out.println("The average value is " + value);
         },
         // Alert the user that there is no value
         () -> {
            System.out.println("No average could be determined!");
         }
      ); // end ifPresentOrElse()

      return average.orElse(Double.NaN);
   } // end getAverageWithStream()
乔·H

根据@Robert Bain留下的评论,我的方法需要按以下方式进行更改以支持中位数聚合:

   /**
    * Function to find median element from a List of Integers in Java 9 and above
    * @param list List<Double>
    * @return Double
    */
   public static Double getMedianWithStream(List<Double> list) {
      DoubleStream sortedNumbers = list.stream() // Stream<Double>
                                 .mapToDouble(v -> v) // DoubleStream
                                 .sorted(); // DoubleStream sorted

      OptionalDouble median = (
         list.size() % 2 == 0 ?
         sortedNumbers.skip((list.size() / 2) - 1)
                     .limit(2)
                     .average() :
         sortedNumbers.skip(list.size() / 2)
                     .findFirst()
      );

      // Print out a message about the 'average' variable's value
      // Note: ifPresentOrElse() was introduced in JDK9
      median.ifPresentOrElse(
         // message the value if one exists
         (value) -> {
            System.out.println("The median value is " + value);
         },
         // Alert the user that there is no value
         () -> {
            System.out.println("No median could be determined!");
         }
      ); // end ifPresentOrElse()

      return median.orElse(Double.NaN);
   } // end getAverageWithStream()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章