【问题标题】:The method flatMapping((<no type> dish) -> {}, toSet()) is undefined for the type Grouping方法 flatMapping((<no type> disc) -> {}, toSet()) 对于 Grouping 类型是未定义的
【发布时间】:2019-02-03 17:14:55
【问题描述】:

我正在使用 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())));
    }
}

【问题讨论】:

  • 注意:建议您分享问题中的代码而不是图像,以便于重现。

标签: java java-8 java-stream collectors


【解决方案1】:

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

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 API in Collectors 是在 Java-9 中引入的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-21
    • 2013-11-11
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多