How to condense the following in Java 8

The car has many manufactures, and I want to collect all the manufacturers in the kit. For instance:

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 an output to contain all manufacturers (without redundancy)

Now:

 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 one set (not nested).

[EDIT] What if some objects are null for manufacturers and we want to prevent NPE?

+5
source share
2 answers

Use flatMap :

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

If you want to avoid Car creating null , add a filter:

 Set<String> manufactures = carList.stream() .filter(c -> c.getManufacturers() != null) .flatMap(c -> c.getManufacturers().stream()) .collect(Collectors.toSet()); 
+5
source

Another option for using method references for brevity only is to map from Car to List<String> , filter from null lists, smooth the stream of streams, and then finally assemble it into the Set implementation.

 Set<String> resultSet = carList.stream() .map(Car::getManufacturers) .filter(Objects::nonNull) .flatMap(List::stream) .collect(Collectors.toSet()); 
0
source

Source: https://habr.com/ru/post/1274619/


All Articles