有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java类型不匹配:无法从Set<Object>转换为Set<Long>

我有这个密码

Set<Long> families = humans
            .stream()
            .flatMap(x -> x.data.stream().map(l -> l.person.id))
            .collect(Collectors.toSet());

humans = List<Human>

public static class Human
{
    public List<Data> data = Lists.newArrayList();
}    

public static class Data
{
    public Person person;
}

public class Person
{
   public long id;
   public String name; 
}

由于以下错误,此代码无法工作:

Type mismatch: cannot convert from Set to Set Why do I have this error? Did I do something wrong?


共 (1) 个答案

  1. # 1 楼答案

    我不知道为什么会出错,但作为解决办法:

    Set<Long> families = humans
                .stream()
                .flatMap(x -> x.data.stream().map(l -> l.person.id)).map(f->(Long) f)
                .collect(Collectors.toSet());
    

    或者(感谢@Tunaki):

    Set<Long> families = humans
                    .stream()
                    .<Long>flatMap(x -> x.data.stream().map(l -> l.person.id))
                    .collect(Collectors.toSet());
    

    或者我可以使用循环,在这种情况下,il比使用流更快