33

I have a class like this

public class Example {
    private List<Integer> ids;

    public getIds() {
        return this.ids; 
    }
}

If I have a list of objects of this class like this

List<Example> examples;

How would I be able to map the id lists of all examples into one list? I tried like this:

List<Integer> concat = examples.stream().map(Example::getIds).collect(Collectors.toList());

but getting an error with Collectors.toList()

What would be the correct way to achive this with Java 8 stream api?

2

3 Answers 3

58

Use flatMap:

List<Integer> concat = examples.stream()
    .flatMap(e -> e.getIds().stream())
    .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

8 Comments

Can you explain the difference between flatMap and map
@CraigR8806 Extensive explanations here
What would happen if e.getIds() returns an empty list or null? How could a test for empty list or null be included into the statement?
@gabriel "empty list" well, there's nothing in the list, but it would work just the same. "null" a NullPointerException would be thrown. How would you want to handle null; and why would you want to (specially) handle an empty list?
Well you could do something like { List<Integer> ids = e.getIds(); if (ids == null) ids = Collections.emptyList(); return ids.stream(); }. But consider that the null might itself be a bug; so it might be better to fix it rather than work around it.
|
10

Another solution by using method reference expression instead of lambda expression:

List<Integer> concat = examples.stream()
                               .map(Example::getIds)
                               .flatMap(List::stream)
                               .collect(Collectors.toList());

Comments

2

Here is an example of how to use Stream and Map to collect the object list:

List<Integer> integerList = productsList.stream().map(x -> x.getId()).collect(Collectors.toList());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.