Jen*_*ols 7 java dictionary hashmap
我想知道是否可以从 HashMap 中获取随机值,然后直接从 HashMap 中删除该键/值?我似乎找不到任何有效的方法,不同的数据结构是否更适合这个?
编辑:我应该更清楚,我生成一个随机数,然后检索与该随机数对应的值。我需要返回该值,然后从地图中删除该条目。
返回和从 a 中删除键值对的最佳方法HashMap是使用该remove(key)方法。此方法删除与 关联的条目key并返回其相应的值。
Integer randomNumber = new Random().nextInt(10);
Map<Integer, String> map = new HashMap<>();
String valueOfRandomNumberKey = map.remove(randomNumber);
Run Code Online (Sandbox Code Playgroud)
也许Map#computeIfPresent适合你的情况。从它的文档来看:
如果指定键的值存在且非空,则尝试在给定键及其当前映射值的情况下计算新映射。
如果重映射函数返回 null,则删除映射。
var map = new HashMap<Integer, String>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
map.computeIfPresent(2, (k, v) -> {
// `v` is equal to "Two"
return null; // Returning `null` removes the entry from the map.
});
System.out.println(map);
Run Code Online (Sandbox Code Playgroud)
上面的代码输出如下:
{1=One, 3=Three}
Run Code Online (Sandbox Code Playgroud)
如果您要使用 a ConcurrentHashMap,那么这将是一个原子操作。
| 归档时间: |
|
| 查看次数: |
8103 次 |
| 最近记录: |