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

Easy way to collect multiple attributes of objects from a list

If I’ve got a list of objects that has multiple attributes of the same type, what is the best way to collect all attributes of the list?

        class Issue {

            Long id1;
            Long id2;
            
            //with appropriate getters
        }
        List<Issue> is = //some list of Issue

        // Is there a better way to do the following? 

        Set<Long> allIds = is.stream().map(i->i.getId1()).collect(Collectors.toSet());
        allIds.addAll(is.stream().map(i->i.getId2()).collect(Collectors.toSet()));

>Solution :

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

You can use mapMulti if you’re on at least Java 16 or flatMap otherwise;

is.stream()
    .mapMulti((issue, mapper) -> {
        mapper.accept(issue.getId1());
        mapper.accept(issue.getId2());
    })
    .collect(Collectors.toSet())

Or:

is.stream()
    .flatMap(issue -> Stream.of(issue.getId1(), issue.getId2()))
    .collect(Collectors.toSet())
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