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?

Andy Turner
141k11 gold badges168 silver badges261 bronze badges
asked Apr 28, 2017 at 14:02
2

3 Answers 3

58

Use flatMap:

List<Integer> concat = examples.stream()
 .flatMap(e -> e.getIds().stream())
 .collect(Collectors.toList());
answered Apr 28, 2017 at 14:04
8
  • Can you explain the difference between flatMap and map Commented Apr 28, 2017 at 14:06
  • 6
    @CraigR8806 Extensive explanations here Commented Apr 28, 2017 at 14:08
  • 1
    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? Commented Aug 24, 2017 at 10:08
  • 1
    @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? Commented Aug 24, 2017 at 10:13
  • 1
    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. Commented Aug 24, 2017 at 10:22
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());
answered Apr 28, 2017 at 15:13
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());
bric3
42.5k9 gold badges99 silver badges116 bronze badges
answered Jan 20, 2024 at 14:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.