javadictionarycollections

Delete all items from Java Map that match specific condition


Following situation. I have:

public class Management {

    private Map<Integer, Book> allBooks = new HashMap<>();

    public void deleteAllBooksFromOwner(Owner owner) {
    }
    
    public class Owner {
        private String name;
        // getters
    }

    public class Book {
        private Owner owner;
        // getters
    }
}

I want to write a method in Management class to delete books:

public void deleteAllBooksFromOwner(Owner owner){
}

I don't know how to access the book owner, for my comparison. Getters are available.


Solution

  • You can use removeIf

    public void deleteAllBooksFromOwner(Owner owner) {
        allBooks.entrySet().removeIf(entry -> entry.getValue().getOwner().equals(owner));
    }