我有一个对象映射,如果对象属性满足特定条件,我想从映射中删除它。地图如下Map<String, ExchangeSummaryItem> under20 = mapper.readValue(new URL("https://rsbuddy.com/exchange/summary.json"), new TypeReference<Map<String, ExchangeSummaryItem>>() {});每个 ExchangeSummary 都有一个sell_average、sell_quantity和buy_quantity,如果sell_average > 2000,并且买入/卖出数量均为 0,我想将其从地图中删除。我当前的代码如下所示,但无法成功从映射中删除任何值(映射仍然具有相同的大小)for (ExchangeSummaryItem item : under20.values()) { int ObjSellAverage = item.getSellAverage(); int ObjSellQ = item.getSellQuantity(); int ObjBuyQ = item.getBuyQuantity(); if (ObjSellAverage > 20000 && ObjSellQ == 0 && ObjBuyQ == 0){ System.out.println(under20.size()); under20.remove(item); }}任何关于为什么会发生这种情况的帮助将不胜感激!谢谢!
1 回答
皈依舞
TA贡献1851条经验 获得超3个赞
under20.remove(item);是使用值进行调用。它期待钥匙。你也不能只是改为迭代和调用,因为你会有一个.removeunder20.keySet()removeConcurrentModificationException
解决它的一种简单方法是创建另一个地图:
Map<String, ExchangeSummaryItem> result = new HashMap<>();
//Map.entrySet() gives you access to both key and value.
for (Map.Entry<String,ExchangeSummaryItem> item : under20.entrySet()) {
int ObjSellAverage = item.getValue().getSellAverage();
int ObjSellQ = item.getValue().getSellQuantity();
int ObjBuyQ = item.getValue().getBuyQuantity();
if (!(ObjSellAverage > 20000 && ObjSellQ == 0 && ObjBuyQ == 0)){
result.put(item.getKey(), item.getValue());
}
}
并在result
添加回答
举报
0/150
提交
取消