java 相同的对象,关于java:列出共享相同属性的对象

本问题已经有最佳答案,请猛点这里访问。

好的,所以基本上我尝试迭代

private ArrayList recordedTemperature;

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

public Temperatures(int location, int day, double temperature)

{

this.location = location;

this.day = day;

this.temperature = temperature;

}

我如何迭代温度数组列表中的所有对象,找出那些具有匹配位置属性的对象并返回它们?

对于您来说,流可能过于复杂,但请使用for循环和if语句。一旦你了解了基础知识,就直截了当地向前看。

更容易阅读:stackoverflow.com/questions/34506218/…

是的,我想应该是for循环或者类似的东西。但我的意思是我该怎么做呢?我有点困惑,因为对于字符串,我会使用if.contains(searchString),但我不确定如何使用int

您没有字符串或int的列表,您有Temperatures对象。您必须执行contains(someTemperature),但这需要的代码比这里需要的多。

可以使用Java 8和流。

要过滤List,请使用过滤器

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

按位置分组使用collect和groupingby

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

您将得到Map,其中key是您的位置,value是给定位置的Temperature列表。

如果您试图根据给定的EDCOX1(1)来获取所有EDCOX1×0,那么您可以在Java 8中这样做:

public List getTemperaturesFromLocation(List temperatures, int location) {

return temperatures

.stream()

.filter(t ->

t.getLocation() == location

)

.collect(Collectors.toList());

}

或者使用正则循环/if语句:

public List getTemperaturesFromLocation(List temperatures, int location) {

List toReturn = new ArrayList<>();

for(Temperatures temperature : temperatures) {

if(temperature.getLocation() == location) {

toReturn.add(temperature);

}

}

return toReturn;

}

你可以尝试一下:

Map> map = new HashMap>(); //create a map, for all location => array of Temperatures objects with this location

for(Temperatures t: recordedTemperatures){

if(map.get(t.location)==null){

map.put(t.location, []); // if it is first Temperatures object with that location, add a new array for this location

}

map.put(t.location, map.get(t.location).push(t)); // get the Temperatures with this location and append the new Temperatures object

}

然后迭代这些映射以获取所有组:

for (Map.Entry>> entry : map.entrySet())

{

// entry.getKey() is the location

// entry.getValue() is the array of Temperatures objects with this location

}

请注意,我没有实现并尝试这个方法,但它可能会起作用,或者给您一个想法。

您需要遍历您的列表,并根据您的条件验证列表中的每个项目。在您的情况下,需要传递列表并标识所有唯一的位置(例如,将它们放在地图中),并为每个位置添加具有该位置的条目列表。

Map> tempsByLocation = new HashMap<>();

for (Temperatures t : recordedTemperature) {

//1 check that there is such location

//2 if there is already, then append your location to the list at that location

//3 otherwise create the new key (new location) and add the new list containing only your temperature to it

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值