Java 8 - Streams API reduce method

Java 8 - Streams API reduce method
java
Ethan Jackson

POJO: Employee{id=155, name='Nima ', age=27, gender='Female', department='HR', yearOfJoining='17/10/2001', salary=42700.0, hobbies=[Tennis, Chess, Guitar]}

Goal: Get Total Count of All Employee hobbies.

I want to use Streams.reduce 3rd overloaded method to achieve this.

My attempt so far:

BinaryOperator<Integer> hobbiesCountCombiner = Integer::sum; BiFunction<List<String>, Integer, Integer> hobbiesCountAccumulator = (hobbies, count) -> hobbies.size() + count; System.out.println( EmployeeDatabase.getEmployeeList().stream() //Stream<Employee> .map(Employee::getHobbies) // Stream<List<String>> .reduce(0, // Compile Time Error hobbiesCountAccumulator, hobbiesCountCombiner ) );

CompileTime Error :

no instance(s) of type variable(s) exist so that List conforms to Integer

I am either getting confused or unclear on the fundamentals, can you please suggest what am I doing wrong here. As far as my understanding goes the BiFuntion should be able to convert types from List to Integer.

P.S This is just for self learning, doesn't reflect real world porblem.

Answer

The parameters of the accumulator should be the other way around. The first parameter should be the Integer, and the second parameter should be the List<String>.

BiFunction<Integer, List<String>, Integer> hobbiesCountAccumulator = (count, hobbies) -> hobbies.size() + count;

Related Articles