Java 8 group by String

前端 未结 1 1191
小鲜肉
小鲜肉 2020-12-06 21:27

Here is my code:

public class StudentData {

    public static List getData() {

        return Arrays.asList(
            new Student(1, \"a1         


        
相关标签:
1条回答
  • 2020-12-06 21:37

    You basically need a Stream that is made out of a Pair (I choose AbstractMap.SimpleEntry here) that has the left part as a Hobby and right as the Student (could be the other way around, does not matter).

    Later just group those based on Hobby (that is a String in your case).

    data.stream()
        .flatMap(student -> student.getHobbies().stream().map(hobby -> new SimpleEntry<>(hobby, student)))
        .collect(Collectors.groupingBy(
                Entry::getKey,
                Collectors.mapping(Entry::getValue, Collectors.toList())
    ));
    

    Entry::getKey being a method reference that gets the key, you could write it as a lambda expression too, if it makes more sense for you:

    Collectors.groupingBy(entry -> entry.getKey())
    
    0 讨论(0)
提交回复
热议问题