gpt4 book ai didi

java - 用于求和 java 8 float 的自定义收集器实现

转载 作者:行者123 更新时间:2023-12-02 00:29:17 24 4
gpt4 key购买 nike

我正在尝试创建类似于 Collectors.summingDouble() 的自定义 float 添加。 .

但我面临两个问题,我不知道如何解决它。

  1. BiConsumer - 第 #27 行 - void 方法不能返回值
  2. Collectors.of - 第 32 行 - Collector 类型中的 (Supplier, BiConsumer<R,T> , BinaryOperator<R> , Collector.Characteristics...) 方法不适用于参数( Supplier<Float[]>BiConsumer<Float,Employee>BinaryOperator<Float> )这里需要做什么来解决这个问题?
public class CustomCollector {


public static void main(String[] args) {
Employee e1=new Employee(1,"Tom",10.2f);
Employee e2=new Employee(1,"Jack",10.4f);
Employee e3=new Employee(1,"Harry",10.4f);
ArrayList<Employee> lstEmployee=new ArrayList<Employee>();
lstEmployee.add(e1);lstEmployee.add(e2);lstEmployee.add(e3);

/* Implementation 1
* double totalSal=lstEmployee.stream().collect(Collectors.summingDouble(e->e.getSal()));
System.out.println(totalSal);
*/
//Implementation 2
Function<Employee,Float> fun=(e)->e.getSal();
BiConsumer<Float,Employee> consumer=(val,e)->val+e.getSal();
BinaryOperator<Float> operator=(val1,val2)->val1+val2;
Supplier<Float[]> supplier=() -> new Float[2];

float FtotalSal=lstEmployee.stream().collect(
Collector.of(supplier,consumer,operator));
System.out.println(FtotalSal);
}

}

class Employee {
int id;
String name;
float sal;
// getters, setter, constructror
}

最佳答案

看来,你很困惑ReductionMutable Reduction .

您的函数 (val, e) -> val + e.getSal()(val1, val2) -> val1 + val2) 适用于归约操作,但不适用于collect。供应商生成了一个长度为 2 的 Float[] 数组,根本不适合它。

例如,您可以使用执行操作

float f = lstEmployee.stream().reduce(
0F,
(val, e) -> val + e.getSal(),
(val1, val2) -> val1 + val2);

这会带来一些装箱开销,因为所有中间总和都表示为 Float 对象。

您可以使用 Mutable Reduction 来避免这种情况,当您创建一个能够容纳 float 值而无需装箱的可变容器时,即 new float[1]。然后,您必须提供接受数组参数并更改所包含值的函数。由于您的预期结果是一个float,而不是一个数组,因此您还需要一个finisher来生成最终结果。

float f = lstEmployee.stream().collect(
Collector.of(
() -> new float[1], // a container capable of holding one float
(floatArray,e) -> floatArray[0] += e.getSal(), // add one element to the array
(a1, a2) -> { a1[0] += a2[0]; return a1; }, // merge two arrays
array -> array[0]) // extracting the final result value
);

当然,这仅用于练习,因为您已经证明了使用内置功能了解更简单的解决方案。

关于java - 用于求和 java 8 float 的自定义收集器实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61862623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com