Skill Week -8_Functional Interfaces, Lambda Expressions, Map and Stream API
Skill Week -8_Functional Interfaces, Lambda Expressions, Map and Stream API
Explanation:
1 Transaction Class:
This class represents each transaction with two fields: amount (of type
double) and category (of type String).
There are two getter methods, getAmount() and getCategory(), used for
accessing these fields.
2 Stream Operations:
The transactions.stream() method initiates a stream pipeline on the list of
transactions.
We use Collectors.groupingBy() to group the transactions by category.
The first argument to groupingBy() is a method reference
Transaction::getCategory, which extracts the category of each
transaction.
The second argument is a collector Collectors.summingDouble(), which
sums the amounts of transactions. This is achieved using a lambda
expression (t -> t.getAmount()) that extracts the amount of each
transaction.
3 Result:
The transactions are grouped by their category, and the sum of the
transaction amounts is computed for each category.
Finally, the forEach() method is used to print the total amount for each
category.
Explanation
1 StudentGrade Class: Holds data for each grade entry, including the subject and
the grade.
2 AverageGradeCollector Class:
supplier: Provides a new HashMap to collect grades by subject.
accumulator: Adds grades to the list corresponding to each subject.
combiner: Merges two maps by combining lists of grades.
finisher: Computes the average grade for each subject from the collected
lists.
3 Parallel Stream Processing:
Use parallelStream() to process the grades list in parallel.
Collect results using AverageGradeCollector.