Bird
Raised Fist0

Which Kafka Streams code snippet correctly performs this aggregation?

hard🚀 Application Q15 of Q15
Kafka - Streams
You want to compute the total sales amount per product category from a Kafka stream sales where each record has category and amount. Which Kafka Streams code snippet correctly performs this aggregation?
Asales.groupBy((key, sale) -> sale.category).aggregate(() -> 0.0, (key, newVal, agg) -> agg + newVal.amount);
Bsales.groupBy((key, sale) -> sale.category).reduce((agg, newVal) -> agg + newVal.amount);
Csales.groupByKey().count();
Dsales.countBy((key, sale) -> sale.category);
Step-by-Step Solution
Solution:
  1. Step 1: Choose aggregation method for summing amounts

    To sum amounts, use aggregate() with initializer and adder function.
  2. Step 2: Verify groupBy key selector and aggregation logic

    Grouping by sale.category and adding newVal.amount to accumulator is correct.
  3. Final Answer:

    sales.groupBy((key, sale) -> sale.category).aggregate(() -> 0.0, (key, newVal, agg) -> agg + newVal.amount); -> Option A
  4. Quick Check:

    aggregate with initializer sums amounts per category [OK]
Quick Trick: Use aggregate() with initializer to sum values per group [OK]
Common Mistakes:
MISTAKES
  • Using reduce() without matching types
  • Calling count() instead of sum
  • Using non-existent countBy() method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kafka Quizzes