Home > front end >  Is there a shorthand way to write this using Java stream/lambda?
Is there a shorthand way to write this using Java stream/lambda?

Time:12-11

Suppose I have a collection

Map<String, List<String>> names;

If I want to print each name, this would work

for(String location: names.keySet()) {
    for(String name: names.get(location) {
        System.out.println(name);
    }
}

Is there a shorthand/more elegant way to rewrite this using Java stream/lambda?

CodePudding user response:

You can use the forEach method

names.forEach((location, nameList) -> {
    nameList.forEach(name -> System.out.println(name));
});

CodePudding user response:

 names.values().stream()
            .flatMap(Collection::stream)
            .forEach(System.out::println);

and here some tutorial for stream api https://dev.java/learn/the-stream-api/

hope that help and have a nice day :)

  • Related