Search code examples
javahashmap

Remove multiple keys within a HashMap (Java)


Any way to delete multiple keys in one shot?

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);
            }
    }
}

Solution

  • You're probably looking for the removeIf which will allow you to remove elements from the HashMap which meet a certain criteria as defined by the predicate passed in.

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

    Using this example:

            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);
    

    The output is:

    keySet after removal = [third, first]