方法收集(收集器<?super Dish,A,R>)类型Stream< Dish>不适用于参数(收集器< CharSequence,捕获#3-of?,String>) [英] method collect(Collector<? super Dish,A,R>) in the type Stream<Dish> not applicable for the arguments (Collector<CharSequence,capture#3-of ?,String>)

查看:213
本文介绍了方法收集(收集器<?super Dish,A,R>)类型Stream< Dish>不适用于参数(收集器< CharSequence,捕获#3-of?,String>)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面开发的Java 8代码中遇到以下错误。在此示例中,尝试将Dish Name的所有名称连接到单个变量中。使用下面的代码我得到了这个Stream< Dish>类型中的方法collect(Collector<?super Dish,A,R>)不适用于参数(Collector< CharSequence,capture#3) -of?,String>)

I am getting the below error for Java 8 code developed below. In this example, trying to join all the names of the Dish Name into a single variable. With the below code I got this "The method collect(Collector<? super Dish,A,R>) in the type Stream<Dish> is not applicable for the arguments (Collector<CharSequence,capture#3-of ?,String>)".

Dish.java

@Builder
@Data
@AllArgsConstructor
public class Dish {
    public enum Type { MEAT, FISH, OTHER }

    private final String name;
    private final boolean vegetarian;
    private final int calories;
    private final Type type;

    public static final List<Dish> menu =
            Arrays.asList( new Dish("pork", false, 800, Dish.Type.MEAT),
                           new Dish("beef", false, 700, Dish.Type.MEAT),
                           new Dish("chicken", false, 400, Dish.Type.MEAT),
                           new Dish("french fries", true, 530, Dish.Type.OTHER),
                           new Dish("rice", true, 350, Dish.Type.OTHER),
                           new Dish("season fruit", true, 120, Dish.Type.OTHER),
                           new Dish("pizza", true, 550, Dish.Type.OTHER),
                           new Dish("prawns", false, 400, Dish.Type.FISH),
                           new Dish("salmon", false, 450, Dish.Type.FISH));
}

这是主要方法

String shortMenu = Dish.menu.stream().map(Dish::getName).collect(joining());
System.out.println(shortMenu);

String shortMenu1 = Dish.menu.stream().collect(joining()); //line-3


推荐答案

你有龙目岛注释 @Data 会自动创建一个 toString()方法,所以大概你期望第3行能够正常工作。 toString()方法仅在将其添加到字符串(即文字字符串或另一个声明为String的变量)时自动调用。对于其他用途,您需要显式调用 toString()。因此,第3行应为:

You've got the Lombok annotation @Data which automatically creates a toString() method, so presumably you were expecting line-3 to work. The toString() method is only called automatically when you add it to a string (i.e. a literal string or another variable declared as String). For other uses, you need to call toString() explicitly. Therefore, line-3 should be:

String shortMenu1 = Dish.menu.stream().map(Dish::toString).collect(joining()); //line-3

这篇关于方法收集(收集器&lt;?super Dish,A,R&gt;)类型Stream&lt; Dish&gt;不适用于参数(收集器&lt; CharSequence,捕获#3-of?,String&gt;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆