【发布时间】:2015-04-30 18:32:03
【问题描述】:
我一直在寻找一种简短易读的方法来从哈希图中删除条目。 具体来说,这是我的方法:
Map<String, HashMap<String, Long>> kitcooldowns = new HashMap<String, HashMap<String, Long>>();
// METHOD TO REMOVE EXPIRED COOLDOWNS FROM HASHMAP
final long currentime = System.currentTimeMillis();
final HashMap<String, HashMap<String, Long>> tmp = new HashMap<String, HashMap<String,Long>>();
for (final Entry<String, HashMap<String, Long>> kits : kitcooldowns.entrySet()) {
final HashMap<String, Long> newitems = new HashMap<String, Long>();
for (final Entry<String, Long> item : kits.getValue().entrySet()) {
if (item.getValue() + getCooldownTime(item.getKey()) > currentime) {
newitems.put(item.getKey(), item.getValue());
}
}
if (newitems.isEmpty() == false) tmp.put(kits.getKey(), newitems);
}
kitcooldowns = tmp;
private long getCooldownTime(final String type) {
switch (type) {
case "CooldownX":
return 3600000;
case "CooldownY":
return 1800000;
default:
return 0L;
}
}
为了简化,这是主要结构:
MAP<NAME OF PLAYER, MAP<TYPE OF COOLDOWN, TIME WHEN USED>>
如果特定的冷却时间已过期,则玩家将从哈希图中移除。 现在,这对我来说似乎是一个混乱的解决方案,我相信还有更好的解决方案。
编辑: 我的问题是,如果 Java 8 有一种高效且干净的方法(如迭代器),它为大多数长方法提供了大量新的单行解决方案。
【问题讨论】: