java stream for grouping by multiple keys

56 Views Asked by At

I'm trying to group a list of objects which contains nested list of keys in, and the data structure looks like:


class BookInformation {
     String accountId;
     String bookName;
     String bookId;
     List<Info> infos;
}

class Info {
    String type;
    String detail;
}

class GroupedInformation {
     String accountId;
     Info info;
     List<String> bookNames;
}

So say if the input is a List of BookInformation, and to be grouped by the account and info together and the output is List of GroupedInformation, I'm trying to use

List<GroupedInformation> groupBy(List<BookInformation> toGroup) {
    return toGroup.stream.collect(groupingBy(BookInformation::getAccountId), Collectors.??);
}

though not sure how to flat the List<List> and grouping again by the info to get the list of the bookName there without introducing some new data structure like Map<Info, List>, etc. Any thoughts?

Added a test for this:

void test() {
        List<BookInformation> toGroup = List.of(
                new BookInformation("account1", "bookName1", "book1", List.of(new Info("info1", ""), new Info("info2", ""))),
                new BookInformation("account1","bookName2", "book2", List.of(new Info("info2", ""), new Info("info3", ""))),
                new BookInformation("account2","bookName3", "book3", List.of(new Info("info3", ""), new Info("info4", "")))
        );

        List<GroupedInformation> grouped = groupBy(toGroup);

        assertThat(grouped).containsExactlyInAnyOrder(
                new GroupedInformation("account1", new Info("info1",""), List.of("bookName1")),
                new GroupedInformation("account1", new Info("info2",""), List.of("bookName1", "bookName2")),
                new GroupedInformation("account1", new Info("info3",""), List.of("bookName2")),
                new GroupedInformation("account2", new Info("info3",""), List.of("bookName3")),
                new GroupedInformation("account2", new Info("info4",""), List.of("bookName3"))
        );
                
                
    }
0

There are 0 best solutions below