Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to condense the following in Java 8

Tags:

java

java-8

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 Lists, 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?

like image 531
JavaDeveloper Avatar asked Jan 10 '18 15:01

JavaDeveloper


1 Answers

Use flatMap:

Set<String> manufactures =
    carList.stream()
           .flatMap(c -> c.getManufacturers().stream())
           .collect(Collectors.toSet());

If you want to avoid Cars having null manufactures, add a filter:

Set<String> manufactures =
    carList.stream()
           .filter(c -> c.getManufacturers() != null)
           .flatMap(c -> c.getManufacturers().stream())
           .collect(Collectors.toSet());
like image 191
Eran Avatar answered Nov 14 '22 22:11

Eran