Fly*_*n51 1 java collections treemap
我创建了一个TreeMapwith 产品。
我想计算它们重复的次数,但不知道要编码什么。有什么提示吗?(我期望没有代码,只是建议)
private static Map<Integer, String> shoppingCart() {
Map<Integer, String> result = new TreeMap<>();
result.put(1, "sausage");
result.put(2, "sausage");
result.put(3, "soup");
result.put(4, "egg");
result.put(5, "egg");
result.put(6, "tomato");
result.put(7, "sausage");
return result;
}
Run Code Online (Sandbox Code Playgroud)
我正在考虑添加一个计数变量,但仍然不能解决重复问题。
也许不是最好的方法,但在不修改已有内容的情况下,您可以使用另一个映射将产品存储为键,将数量存储为这些键的值:
Map<Integer, String> result = shoppingCart();
Map<String, Integer> productQuantities = new HashMap<>();
result.values().forEach(value ->
productQuantities.put(value,productQuantities.getOrDefault(value, 0) + 1));
Run Code Online (Sandbox Code Playgroud)
要打印结果地图:
productQuantities.forEach((key, value) -> System.out.println(key + ":" + value));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
284 次 |
| 最近记录: |