How to calculate the average value of multiple numbers sequentially using java 8 lambda

If I have a collection point, how can I use the Java 8 stream to calculate the average of X and Y in a single iteration

The following example creates two flows & iterating over the input set twice to calculate the X & year Are they any way computers average x, y in a single iteration using java 8 lambda:

List<Point2D.Float> points = 
Arrays.asList(new Point2D.Float(10.0f,11.0f),new Point2D.Float(1.0f,2.9f));
// java 8,iterates twice
double xAvg = points.stream().mapToDouble( p -> p.x).average().getAsDouble();
double yAvg = points.stream().mapToDouble( p -> p.y).average().getAsDouble();

Solution

If you don't mind using additional libraries, we have recently added tuple collector support to jeoo λ.

Tuple2<Double,Double> avg = points.stream().collect(
    Tuple.collectors(
        Collectors.averagingDouble(p -> p.x),Collectors.averagingDouble(p -> p.y)
    )
);

In the code above, tuple Collectors () will several Java util. stream. Collector instances are combined into a collector to collect values into a tuple

This is more concise and reusable than any other solution The price you have to pay is that the current operation is the wrapper type, not the original double I think we must wait until Java 10 and project Valhalla for primitive type specialization in genetics

If you want to scroll by yourself instead of creating dependencies, the relevant methods are as follows:

static <T,A1,A2,D1,D2> Collector<T,Tuple2<A1,A2>,Tuple2<D1,D2>> collectors(
    Collector<T,D1> collector1,Collector<T,D2> collector2
) {
    return Collector.of(
        () -> tuple(
            collector1.supplier().get(),collector2.supplier().get()
        ),(a,t) -> {
            collector1.accumulator().accept(a.v1,t);
            collector2.accumulator().accept(a.v2,t);
        },(a1,a2) -> tuple(
            collector1.combiner().apply(a1.v1,a2.v1),collector2.combiner().apply(a1.v2,a2.v2)
        ),a -> tuple(
            collector1.finisher().apply(a.v1),collector2.finisher().apply(a.v2)
        )
    );
}

Tuple2 is just a simple wrapper of two values You can also use abstractmap Simpleimmutableentry or something like that

I also introduced this technology in detail in an answer to another stack overflow question

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>