Reputation: 113
Im new to Java 8. Im trying to build the studentlist here and i want to return the List by setting student name from the List of getStudentNames(). I want to split this String with space and loop each split words and assign each words(“orange”, “yellow”, “blue”) in withBadge below for every student name in the loop.
private static List<Student> buildStudentList(String badge) {
//TODO: i want to stream the list of Splitted Strings here and modify the list below.
return getStudentNames()
.stream()
.map(name -> new Student.Builder()
.withName(name)
.withBadge(badge)
.build()).collect(Collectors.toList());
}
protected static List<StudentNames> getStudentNames() {
return List.of(“sam”, “andrew”, “joseph”);
}
i tried something like below:
List<String> splitBadges = Stream.of(badge.split("\\s")).collect(Collectors.toList());
I tried with for each method on above list but it’s not working as i already have one more loop and want to return student list . It says expected void method and not able to return what I want .Can someone please help here with how to loop this ?
this is the sample output im expecting :
student: [
{
name: "sam",
badge: "orange"
},
{
name: "andrew",
badge: "orange"
},
{
name: "joseph",
badge: "orange"
},
{
name: "sam",
badge: "yellow"
},
{
name: "andrew",
badge: "yellow"
},
{
name: "joseph",
badge: "yellow"
},
{
name: "sam",
badge: "blue"
},
{
name: "andrew",
badge: "blue"
},
{
name: "joseph",
badge: "blue"
},
]
Upvotes: 2
Views: 1037
Reputation: 1685
Something like this (importing static Collection.toList()
):
Stream.of(badges.split("\\s"))
.map(badge -> studentNames.stream()
.map(name -> new Student.Builder()
.withName(name)
.withBadge(badge)
.build())
.collect(toList()))
.flatMap(Collection::stream)
.collect(toList());
As pointed out in the comments, this can be greatly simplified and is a much better version:
Stream.of(badges.split("\\s"))
.flatMap(badge -> studentNames.stream()
.map(name -> new Student.Builder()
.withName(name)
.withBadge(badge)
.build()))
.collect(toList());
Upvotes: 2