如何基于两个同Key的Map生成指定数量的Ingredient列表?
实现ingredientsFromIdAndCount方法的思路与代码
不需要反转Map,直接遍历idsAndCount的键值对就能完成需求,具体步骤如下:
- 初始化一个空的
ArrayList<Ingredient>作为结果容器 - 遍历
idsAndCount的键值对集合(entrySet),每个元素包含一个ID和对应的订购数量 - 对每个键值对,通过ID从
articles中取出对应的Ingredient对象 - 根据订购数量,将该
Ingredient重复添加到结果列表中 - 最后返回结果列表
代码实现示例
import java.util.ArrayList; import java.util.Map; public class IngredientProcessor { public ArrayList<Ingredient> ingredientsFromIdAndCount(Map<Long, Integer> idsAndCount, Map<Long, Ingredient> articles) { ArrayList<Ingredient> resultList = new ArrayList<>(); // 遍历idsAndCount的每个键值对 for (Map.Entry<Long, Integer> entry : idsAndCount.entrySet()) { Long ingredientId = entry.getKey(); int count = entry.getValue(); Ingredient ingredient = articles.get(ingredientId); // 确保Ingredient存在的情况下,按数量添加 if (ingredient != null) { for (int i = 0; i < count; i++) { resultList.add(ingredient); } } } return resultList; } // 假设Ingredient类的定义 static class Ingredient { private String name; public Ingredient(String name) { this.name = name; } @Override public String toString() { return name; } } // 测试用例 public static void main(String[] args) { Map<Long, Integer> counts = Map.of(66L, 1, 17L, 2); Map<Long, Ingredient> testMenu = Map.of(42L, new Ingredient("gurken"), 66L, new Ingredient("kaese"), 17L, new Ingredient("fleisch")); IngredientProcessor processor = new IngredientProcessor(); ArrayList<Ingredient> result = processor.ingredientsFromIdAndCount(counts, testMenu); // 输出结果:[kaese, fleisch, fleisch] System.out.println(result); } }
关键说明
- 遍历entrySet:直接遍历
idsAndCount的键值对,能同时拿到ID和数量,比先遍历键再查数量更高效。 - 空值判断:添加
if (ingredient != null)是为了避免articles中不存在对应ID的情况,防止空指针异常。如果业务能保证所有ID都在articles中存在,也可以去掉这个判断。 - 无需反转Map:
articles本身就是以ID为键存储Ingredient,直接通过ID查找即可,反转Map会额外消耗资源,完全没必要。
内容的提问来源于stack exchange,提问作者Escanor
相关产品推荐
相关产品推荐

