1

Here is my code:

public class CarShop {
    private final HashMap<Brand, List<CarPrototype>> catalog;

    public List<CarPrototype> allPrototypes() {
        List<CarPrototype> prototypes = catalog.values().stream().collect(Collectors.toList())
        return prototypes ;
    } 

What I want to do in this method is I want to get a list of all different car prototypes given in car shop catalog. I should not use for loop, so stream comes into play. My solution is adds only lists of prototypes, and I struggle finding how to change it so it add specific prototypes themselves.

2
  • That is a bizzarde to have requiremet to NOT use most common solutions to known problems since the beginning of programming. Commented Apr 6, 2020 at 17:06
  • Well, is there any solution then? Commented Apr 6, 2020 at 17:08

1 Answer 1

3

If you have a Stream<List<Foo>> and want to convert it to List<Foo> you can use flatMap:

Stream<List<Foo>> stream = ...;
Stream<Foo> flatStream = stream.flatMap(List::stream);
List<Foo> list = flatStream.collect(Collectors.toList());

For your specific example:

public List<CarPrototype> allPrototypes() {
    List<CarPrototype> prototypes = catalog.values().stream()
        .flatMap(List::stream)
        .collect(Collectors.toList());
    return prototypes;
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.