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 :

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

Leave a Reply