java 8 中的反向分组

Reverse of grouping in java 8

我可以使用下面的 lamda 表达式对学生列表进行分组。结果将按 "Department" 对学生列表进行分组,然后按 "gender".

分组
Map<String, Map<String, List<Student>>> studentCatg = studentList.stream().collect(groupingBy(Student::getDepartment, groupingBy(Student::getGender)));

现在我需要从上面的 MAP 中获取一个单一列表,其中应该包含特定部门的学生。分组有什么相反的吗?

你可以得到给定部门的EntrySet,通过map组合Map<String, List<Student>>List<List<Student>>到输入设置值然后flatMap到一个List<Student>,像这样:

String department = "department name";
List<Student> students = studentCatg.get(department)
    .values()
    .stream()
    .flatMap(Collection::stream)
    .collect(Collectors.toList())

恢复到初始列表

List<Student> students = studentCatg.values()
        .stream()
        .map(Map::values)
        .flatMap(Collection::stream)
        .flatMap(Collection::stream)
        .collect(Collectors.toList());

我在寻找反转 groupingBy 映射的方法时发现了这个条目,但由于我没有找到通用的解决方案,所以我构建了自己的解决方案,以防万一有人感兴趣。

public static <K, V> Map<V, List<K>> invertGroupByMap(final Map<K, List<V>> src)
{
    return src.entrySet().stream()
            .flatMap(e -> e.getValue().stream().map(a -> new SimpleImmutableEntry<>(a, e.getKey())))
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
}