Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
    }
} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading