Home > Net >  How to add using element to a Collection Set using Streams?
How to add using element to a Collection Set using Streams?

Time:04-04

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()?

CodePudding user response:

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;
    }
} 
  • Related