A Car
has multiple manufactures and I want to gather all manufacturers in a Set
.
For example:
class Car {
String name;
List<String> manufactures;
}
object sedan -> { ford, gm, tesla }
object sports -> { ferrari, tesla, bmw }
object suv -> { ford, bmw, toyota }
Now, I need to create output that contains all manufactures ( without redundancy )
I tried:
carList.stream().map(c -> c.getManufacturers()).collect(Collectors.toSet());
This gives me a Set
of List
s, but I need to get rid of nesting and just create a single Set
( non nested ).
[EDIT] What if some objects have 'null' value for manufactures and we want to prevent NPE?
Use flatMap
:
Set<String> manufactures =
carList.stream()
.flatMap(c -> c.getManufacturers().stream())
.collect(Collectors.toSet());
If you want to avoid Car
s having null
manufactures, add a filter:
Set<String> manufactures =
carList.stream()
.filter(c -> c.getManufacturers() != null)
.flatMap(c -> c.getManufacturers().stream())
.collect(Collectors.toSet());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With