java - 如何在 Java 中存储 <String, List<String>>?

标签 java dictionary

假设我必须实现一家餐厅的菜单,并且我有不同的菜肴名称及其各自的成分。

例如:

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/

相关文章:

java - 套接字发送和检索

java - Android Espresso 测试中的 stub /模拟意图

java - Swing 更新谜题

Python 将哈希值转换为数据帧

dictionary - F# 选项字典

java - 线程转储被阻止并锁定

java - 覆盖的单元素 Java 数据结构

php - 使用递归函数解码字谜不会给出预期的输出

python - 3 级字典 python 不明显

python - 从字典中删除 NoneTypes