Group stock by how soon it expires
A food depot dashboard puts every batch into one of four buckets so staff can see what to move first.
- Below zero days is "expired"; 0 to 7 is "week"; 8 to 30 is "month"; anything more is "later".
- All four keys appear in the result, even when the count is zero.
expiryBuckets(daysLeft: list<int>) → map<string, int>
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
Map<String, Integer> expiryBuckets(List<Integer> daysLeft) {
}
Worked examples
| Call | Result |
|---|---|
expiryBuckets(Main.<Integer>ls(-1, 0, 7, 8, 30, 31, 400)) | Main.<String, Integer>mp("expired", 1, "week", 2, "month", 2, "later", 2) |
expiryBuckets(Main.<Integer>ls()) | Main.<String, Integer>mp("expired", 0, "week", 0, "month", 0, "later", 0) |
expiryBuckets(Main.<Integer>ls(-5, -5, -5)) | Main.<String, Integer>mp("expired", 3, "week", 0, "month", 0, "later", 0) |
expiryBuckets(Main.<Integer>ls(0)) | Main.<String, Integer>mp("expired", 0, "week", 1, "month", 0, "later", 0) |
Hint
Seed the map with all four keys at zero first, then walk the list once.
Reference solution in Java
Map<String, Integer> expiryBuckets(List<Integer> daysLeft) {
Map<String, Integer> out = new LinkedHashMap<>();
out.put("expired", 0); out.put("week", 0); out.put("month", 0); out.put("later", 0);
for (int d : daysLeft) {
String k = d < 0 ? "expired" : d <= 7 ? "week" : d <= 30 ? "month" : "later";
out.put(k, out.get(k) + 1);
}
return out;
}