假设我必须实现一家餐厅的菜单,并且我有不同的菜肴名称及其各自的成分。
例如:
Classic: strawberry, banana, pineapple, mango, peach, honey, ice, yogurt
Forest Berry: strawberry, raspberry, blueberry, honey, ice, yogurt
...
在Python中,我会使用字典来实现这样的事情。稍后,使用这个数据结构,我需要编写一个方法,给出一个字符串,其中首先包含菜名(如果我使用字典,则为键)和一个用逗号分隔的可选成分列表,返回以下成分该菜减去字符串中包含的(如果)。
例如,让我们使用以下配置运行方法ingredients
:
Smoothie.ingredients("Classic,-strawberry,-banana")
我需要的输出是:
"honey,ice,mango,peach,pineapple,yogurt"
我正在寻找最方便的Java数据结构来存储此类对象并执行此类操作。
最佳答案
您应该使用 Map<String,Set<String>>
。因为它是一个键值数据结构。
至于成分我建议Set<String>
,因为我们不关心它们的顺序,但所有成分都必须是唯一的。
下面的代码适用于 JDK11,但也可以重构以在旧版本中工作:
// we normalize key to upper case, to be case insensitive
private Map<String, Set<String>> menu = new HashMap<>();
@BeforeEach
void setUp() { // initialize your menu
menu.put("CLASSIC", Set.of("strawberry", "banana", "pineapple", "mango", "peach", "honey", "ice", "yogurt"));
menu.put("FOREST BERRY", Set.of("strawberry", "raspberry", "blueberry", "honey", "ice", "yogurt"));
}
@Test
void getMissingingredients() {
String key = "classic";
Set<String> startIngredients = Set.of("strawberry", "banana");
// when
Set<String> ingredients = getMissingIngredients(key, startIngredients);
// then
assertEquals(Set.of("pineapple", "mango", "peach", "honey", "ice", "yogurt"), ingredients);
}
private Set<String> getMissingIngredients(String dishName, Set<String> initialIngredients) {
// find dish ingredients by dish name. Copy them to a new HashSet
Set<String> ingredients = new HashSet<>(menu.getOrDefault(dishName.toUpperCase(), Collections.emptySet()));
// remove ingredients that you already have
ingredients.removeAll(initialIngredients);
return ingredients;
}
关于java - 如何在 Java 中存储 <String, List<String>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62913285/