JavaEasy

Top five customers by total spend

You are given a list of transactions. Each one has a customer id and an amount.

Return the five customers who spent the most, highest first. If two customers spent the same, the one whose id sorts first comes first — the result has to be stable, because it is rendered on a dashboard and a list that reshuffles on every refresh looks broken.

Example

inputtx = [("ana", 40), ("bo", 90), ("ana", 70), ("cy", 90)]output["ana", "bo", "cy"]

ana totals 110 and leads. bo and cy both total 90, so the tie breaks on the id and bo comes first.

Constraints

  • 0 ≤ transactions ≤ 1,000,000
  • amounts are non-negative
  • fewer than five distinct customers is valid input

Hints

Hint 1
groupingBy with summingLong, then sort the entry set.
Hint 2
summingInt overflows at about 2.1 billion. The constraint says a million transactions.
Hint 3
limit(5) on a stream of fewer than five elements is not an error.

Stuck? The lesson behind this problem: Streams

java
Tab indents · Escape first to tab out

Test cases

These are the specification. Run tests checks your answer against them.

CaseInputExpected
the example[("ana",40),("bo",90),("ana",70),("cy",90)]["ana","bo","cy"]
fewer than five customers[("ana",1)]["ana"]
empty input[][]
amounts that overflow an int[("ana",3000000000)]["ana"]