gpt4 book ai didi

java - 列出共享相同属性的对象

转载 作者:行者123 更新时间:2023-11-30 07:02:34 26 4
gpt4 key购买 nike

好吧,基本上我正在尝试迭代我的

中的对象
private ArrayList<Temperatures> recordedTemperature;

并显示每个共享相同“位置”的人。该位置是一个在Temperatures类的构造函数中初始化的int变量:

public Temperatures(int location, int day, double temperature)
{
this.location = location;
this.day = day;
this.temperature = temperature;
}

如何遍历Temperatures ArrayList中的所有对象并找出具有匹配位置属性的对象并返回它们?

最佳答案

您可以使用 Java 8 和流。

要过滤列表,请使用 filter

List<Temperature> filtered = recordedTemperature.stream().filter(t -> t.getLocation() == 1).collect(Collectors.toList());

要按位置分组,请使用 collectgroupingBy

Map<Integer, List<Temperature>> grouped = recordedTemperature.stream().collect(Collectors.groupingBy(Temperature::getLocation));

您将获得 map ,其中键是您的位置,值是给定位置的温度列表。

关于java - 列出共享相同属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40649728/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com