How to use Collectors averagingDouble()/averagingInt/averagingLong in Java 8

34 total views, 1 views today

Welcome to Java 8 series. In this tutorial, you will learn about how to use Collectors averagingDouble()/averagingInt/averagingLong in Java 8

If you would like to learn about Java 8 Stream operations. Please check out this link.

Collectors.averagingDouble()/averagingInt/averagingLong in Java 8 is mainly used to identify mean of the stream of elements. If there is scenario or use case to find the average of the elements, then we can very well use this functionality.Each of this function accepts a ToDoubleFunction/ToIntFunction/ToLongFunction and use has to provide an implementation for each function.

So let us get started in learning each operation

Collectors.averagingDouble()

Returns a Collector that produces the arithmetic mean of a double-valued function applied to the input elements.

Syntax

averagingDouble(ToDoubleFunction<? super T> mapper)

Collectors.averagingDouble() Example

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StaticReference
{
public static void main(String[] args)
{

List<Integer> list = Arrays.asList(1, 2, 3, 15, 6, 17, 8);

Double output = list.stream()
.collect(Collectors.averagingDouble(i -> new Double(i)));

System.out.println(output);
}
}

Output

7.428571428571429

Collectors.averagingInt()

Returns a Collector that produces the arithmetic mean of an integer-valued function applied to the input elements.

Syntax

averagingInt(ToIntFunction<? super T> mapper)

Collectors.averagingInt() Example

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StaticReference
{
public static void main(String[] args)
{

List<Integer> list = Arrays.asList(1, 2, 3, 15, 6, 17, 8);

Double output = list.stream().collect(Collectors.averagingInt(i -> i));

System.out.println(output);
}
}

Output

7.428571428571429

Collectors.averagingLong()

Returns a Collector that produces the arithmetic mean of a long-valued function applied to the input elements.

Syntax

averagingLong(ToLongFunction<? super T> mapper)

Collectors.averagingLong() Example

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StaticReference
{
public static void main(String[] args)
{

List<Integer> list = Arrays.asList(1, 2, 3, 15, 6, 17, 8);

Double output = list.stream().collect(Collectors.averagingLong(i -> Long.valueOf(i)));

System.out.println(output);
}
}

Output

7.428571428571429

References : Official documentation

I hope you like this tutorial. Thanks for reading and Please leave us a comment below!

Tags : 