disc) -> {}, toSet()) 未为 Grouping 类型定义,java,java-8,java-stream,collectors"/>

首页 > 解决方案 > 方法 flatMapping((disc) -> {}, toSet()) 未为 Grouping 类型定义

问题描述

我正在使用 Java 8 并且在第 30 行的代码出现以下错误

方法 flatMapping(( disc) -> {}, toSet()) 对于 Grouping 类型是未定义的

public class Grouping {
    enum CaloricLevel { DIET, NORMAL, FAT };

    public static void main(String[] args) {
        System.out.println("Dishes grouped by type: " + groupDishesByType());
        System.out.println("Dish names grouped by type: " + groupDishNamesByType());
        System.out.println("Dish tags grouped by type: " + groupDishTagsByType());
    }


    private static Map<Type, List<Dish>> groupDishesByType() {
        return Dish.menu.stream().collect(groupingBy(Dish::getType));
    }

    private static Map<Type, List<String>> groupDishNamesByType() {
        return Dish.menu.stream().collect(groupingBy(Dish::getType, mapping(Dish::getName, toList())));
    }


    private static String groupDishTagsByType() {
/*line:30*/ return menu.stream().collect(groupingBy(Dish::getType, flatMapping(dish -> dishTags.get( dish.getName() ).stream(), toSet())));
    }
}

在此处输入图像描述

标签: javajava-8java-streamcollectors

解决方案


这可能是因为您期望的返回类型不正确,方法实现应该看起来像:

private static Map<Dish.Type, Set<String>> groupDishTagsByType(Map<String, List<String>> dishTags) {
    return Dish.menu.stream()
            .collect(Collectors.groupingBy(Dish::getType,
                     Collectors.flatMapping(dish -> dishTags.get(dish.getName()).stream(),
                            Collectors.toSet())));
}

注意:我将变量作为参数引入只是为了回答。

重要提示flatMapping APICollectors是随Java-9引入的。


推荐阅读