删除 HashMap 中的多个键 (Java)

Remove multiple keys within a HashMap (Java)

有什么方法可以一次删除多个键吗?

public class AuctionTable extends HashMap<String, Auction> {

public void removeExpiredAuctions() {
    Set<String> keys = this.keySet();
    for (String key : keys) {
            if (this.get(key).getTimeRemaining() == 0) {
                this.remove(key);
            }
    }
}

您可能正在寻找 removeIf,它允许您从 HashMap 中删除符合传入谓词定义的特定条件的元素。

public class AuctionTable extends HashMap<String, Auction> {
    public void removeExpiredAuctions() {
        this.values().removeIf(a -> a.getTimeRemaining() == 0);
    }
}

使用这个例子:

        Auction firstAuction = new Auction(100);
        Auction secondAuction = new Auction(0);
        Auction thirdAuction = new Auction(200);
        Auction fourthAuction = new Auction(0);
        AuctionTable table = new AuctionTable();
        table.put("first", firstAuction);
        table.put("second", secondAuction);
        table.put("third",  thirdAuction);
        table.put("fourth", fourthAuction);
        table.removeExpiredAuctions();
        Set <String> keySet = table.keySet();
        System.out.println("keySet after removal = " + keySet);

输出为:

keySet after removal = [third, first]