【问题标题】:Collect custom object from list of custom objects where object val equals x从对象值等于 x 的自定义对象列表中收集自定义对象
【发布时间】:2021-01-20 22:20:33
【问题描述】:

我正在努力研究如何使用 Java 流从对象值等于 x 的自定义对象列表中收集自定义对象。

考虑我有以下课程:

public class Person {

    private int age;
    private double height;

    public Person(int age, double height) {
        this.age= age;
        this.height = height;
    }

    public int getAge() {
        return age;
    }

    public double getHeight() {
        return height;
    }
}

然后考虑具有这些对象的填充列表,例如List<Person> people.

我的问题是,如何使用流创建一个新的List<Person>,它只包含初始列表中年龄为 35 岁的人员对象?

到目前为止,我有以下内容:

List<Person> peopleAged35 = new ArrayList<>();
peopleAged35.add(people.stream().filter(i -> i.getAge() == 35).map(new Person).collect(Collectors.toList()));

这不会编译,但我认为我离得不远 - 谁能指出我哪里出错了?

【问题讨论】:

    标签: java java-8 java-stream


    【解决方案1】:

    您需要从您的信息流中删除.map(new Person)

    此外,创建new ArrayList 并将其添加到其中也不是绝对必要的; Collectors.toList 会为您返回它——尽管它是只读的。

    【讨论】:

    • 这看起来不起作用,我收到以下问题编译警告:必需类型:提供的人员:列表 没有实例类型变量 T 存在,因此 List 符合 Person
    • 尝试摆脱 .add 所以它只是 List over35 = people.stream()... 问题是 add 方法是通用的,所以不确定返回什么类型。如果您明确提出,它应该可以工作。
    【解决方案2】:
    List<Person> aged35 = people.stream().filter(i -> i.getAge() == 35).collect(Collectors.toList())
    

    不确定为什么要映射到新的 Person。如果您需要获取新对象而不是基本列表中使用的引用,您可能应该克隆对象(并为此创建方法 Person.clone()),例如:

    List<Person> aged35 = people.stream().filter(i -> i.getAge() == 35).map(Person::clone).collect(Collectors.toList())
    

    【讨论】:

    • 这看起来也不错,会考虑 - 谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多