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
3 Answers 3
Use flatMap
:
List<Integer> concat = examples.stream()
.flatMap(e -> e.getIds().stream())
.collect(Collectors.toList());
answered Apr 28, 2017 at 14:04
-
Can you explain the difference between
flatMap
andmap
CraigR8806– CraigR88062017年04月28日 14:06:52 +00:00Commented Apr 28, 2017 at 14:06 -
6@CraigR8806 Extensive explanations hereRobin Topper– Robin Topper2017年04月28日 14:08:06 +00:00Commented Apr 28, 2017 at 14:08
-
1What 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– gabriel2017年08月24日 10:08:50 +00:00Commented 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?Andy Turner– Andy Turner2017年08月24日 10:13:46 +00:00Commented Aug 24, 2017 at 10:13 -
1Well 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.Andy Turner– Andy Turner2017年08月24日 10:22:00 +00:00Commented Aug 24, 2017 at 10:22
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
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
lang-java
getIds
does not have a return type.