java grupo Lambda Corriente Por sumando valores enteros y / media

Migster:

Tengo una lista de objetos de la lista Cliente (Customer: int id, isActive bool, int billingCount, ...) y quiero la suma y el promedio de billingCount. Por desgracia, mi código no funcionaba. ¿Cómo tengo que cambiar el código para que funcione?

suma y promedio mirada sould como esto:

verdadera 1234

falsa 1234

 Map<Boolean, Integer> sum = customer.stream()
                .map(c -> c.getIsActive())
                .collect(Collectors.groupingBy(c -> c, Collectors.summingInt(Customer::getBillingCount)));


Map<Boolean, Integer> average = customer.stream()
                .map(c -> c.getIsActive())
                .collect(Collectors.groupingBy(c -> c, Collectors.averagingInt(Customer::getBillingCount)));
    }

Obtuve el siguiente error:

Error:(146, 17) java: no suitable method found for collect(java.util.stream.Collector<Customer,capture#1 of ?,java.util.Map<java.lang.Object,java.lang.Integer>>)
    method java.util.stream.Stream.<R>collect(java.util.function.Supplier<R>,java.util.function.BiConsumer<R,? super java.lang.Boolean>,java.util.function.BiConsumer<R,R>) is not applicable
      (cannot infer type-variable(s) R
        (actual and formal argument lists differ in length))
    method java.util.stream.Stream.<R,A>collect(java.util.stream.Collector<? super java.lang.Boolean,A,R>) is not applicable
      (inference variable T has incompatible bounds
        lower bounds: java.lang.Object,Customer
        lower bounds: java.lang.Boolean)
Michael Ziober:

No es necesario para el uso map. Véase más abajo ejemplo:

List<Customer> customers = Arrays.asList(
        new Customer(10, true, 5),
        new Customer(11, true, 3),
        new Customer(20, false, 12),
        new Customer(21, false, 11));

Map<Boolean, Integer> sum = customers
        .stream()
        .collect(Collectors.groupingBy(Customer::isActive, Collectors.summingInt(Customer::getBillingCount)));
System.out.println(sum);

Map<Boolean, Double> avg = customers
        .stream()
        .collect(Collectors.groupingBy(Customer::isActive, Collectors.averagingInt(Customer::getBillingCount)));
System.out.println(avg);

imprime el código de seguridad:

{false=23, true=8}
{false=11.5, true=4.0}

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=234776&siteId=1
Recomendado
Clasificación