Lux*_*ode 13 java collections guava
有没有办法在不添加值的情况下将键添加到HashMap?我知道这似乎很奇怪,但我有一个HashMap<String, ArrayList<Object>>amd我想首先能够根据需要创建密钥,然后检查是否存在某个密钥,如果是,则输入适当的值,即ArrayList<Object>
那令人困惑吗?
Mat*_*all 27
既然你正在使用a Map<String, List<Object>>,那么你真的在寻找一个多图.我强烈建议使用Google Guava等第三方库 - 请参阅Guava的Multimaps.
Multimap<String, Object> myMultimap = ArrayListMultimap.create();
// fill it
myMultimap.put("hello", "hola");
myMultimap.put("hello", "buongiorno");
myMultimap.put("hello", "??????");
// retrieve
List<String> greetings = myMultimap.get("hello");
// ["hola", "buongiorno", "??????"]
Run Code Online (Sandbox Code Playgroud)
Java 8更新:我不再相信每一个都Map<K, SomeCollection<V>>应该被重写为多图.这些天很容易在没有番石榴的情况下得到你需要的东西,多亏了Map#computeIfAbsent().
Map<String, List<Object>> myMap = new HashMap<>();
// fill it
myMap.computeIfAbsent("hello", ignored -> new ArrayList<>())
.addAll(Arrays.asList("hola", "buongiorno", "??????");
// retrieve
List<String> greetings = myMap.get("hello");
// ["hola", "buongiorno", "??????"]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39941 次 |
| 最近记录: |