Skip to content
Advertisement

How to add using element to a Collection Set using Streams?

Currently I am adding an element to a Collection Set like this.

Set<Rental> currentFavouriteRentals = currentUser.getFavouriteRentals();
currentFavouriteRentals.add(rental);
currentUser.setFavouriteRentals(currentFavouriteRentals);

Is there a way to do this with Streams that does not use Stream.concat()?

Advertisement

Answer

I would suggest you to remodel the objects, you’re updating User‘s favorites outside this should happen within the User class Read this OO Principle, TellDon’tAsk

class User {
    private Set<Rental> favoriteRentals;

    public User() {
        this.favoriteRentals = new HashSet<>();
    }

    public Set<Rental> updateFavoriteRentals(Rental rental) {
        this.favoriteRentals.add(rental);
        return this.favoriteRentals;
    }
} 
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement