猿问

Java 中的 lambda 表达式 ClassCastException

我正在尝试在 Java 8 中学习流式传输。以下是我的代码:


Main.java


public class Main {

    public static void main(String[] args) {


        Person person = new Person("FirstName", "LastName");

        List<Person> personList = new ArrayList<>();

        personList.add(person);


        Place place = new Place("name", "country");

        List<Place> placeList = new ArrayList<>();

        placeList.add(place);



        List<List<Object>> objects = new ArrayList<>();

        objects.add(Collections.singletonList(personList));

        objects.add(Collections.singletonList(placeList));


        List<Object> persons = objects.get(0);

        List<String> firstNames = persons.stream()

                .map(o -> ((Person)o).getFirstName())

                .collect(Collectors.toList());


        firstNames.forEach(System.out::println);

    }

}

Person.java


@Data

public class Person {

    String firstName;

    String lastName;


    public Person(String firstName, String lastName) {

        setFirstName(firstName);

        setLastName(lastName);

    }

}

Place.java


@Data

public class Place {

    String name;

    String country;


    public Place(String name, String country) {

        setName(name);

        setCountry(country);

    }

}


我持有List其中List的一个Object(我正在使用Object,因为我想使用不同类型的对象存储到集合中)。我正在将 的集合Person和 的集合存储Place到这个List集合中List。


在流媒体中,我试图获得firstName所有人中的唯一。但是,当我使用遍历每个元素并获取 firstName 的 lamba 表达式时,它不适用于转换。

问题:

  1. 我做错了什么吗?

  2. 有没有其他方法(除了map流式传输)通过流 API 获取 Person 对象的所有 FirstName?


慕哥6287543
浏览 142回答 1
1回答

ibeautiful

personList是一个人的名单Collections.singletonList(personList)是人员列表objects是人员/地点列表的列表。&nbsp; &nbsp; List<Object> persons = objects.get(0);&nbsp; &nbsp;// persons is a List of List of Person&nbsp; &nbsp; List<String> firstNames = persons.stream()&nbsp;&nbsp;&nbsp; &nbsp; //each element in the stream is a List of Person, so you cannot cast it to Person.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(o -> ((Person)o).getFirstName())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());您可以删除 singletonList 函数,以便减少列表级别:&nbsp; &nbsp; List<List<?>> objects = new ArrayList<>();&nbsp; &nbsp; objects.add(personList);&nbsp; &nbsp; objects.add(placeList);或者在做地图时更深入地列出一个列表:&nbsp; &nbsp; List<String> firstNames = persons.stream()&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Because persons is declared as List of Objects, so you need to cast each element into a List before calling get&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(o -> ((Person)((List)o).get(0))).getFirstName())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());
随时随地看视频慕课网APP

相关分类

Java
我要回答