2016-11-17 24 views
1

好了,所以基本上我试图通过对象在我上市对象

private ArrayList<Temperatures> recordedTemperature; 

迭代,并显示每一个谁共享相同的“位置”。

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

我将如何通过温度ArrayList中的所有对象进行迭代,并找出谁拥有匹配的位置属性,并返回他们的:位置是一个int变量在温度类的构造函数初始化?

+2

流对于你来说可能太复杂了,但是使用for循环和if语句。非常直接,一旦你知道的基础 –

+0

更容易遵循帖子:http://stackoverflow.com/questions/34506218/find-specific-object-in-a-list-by-attribute –

+0

是的,我想它必须成为一个循环或类似的东西。但我的意思是如何用int来做到这一点?我有点困惑,因为对于字符串我会使用if.contains(searchString),但我不确定如何使用整数执行它 –

回答

0

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

Map<Integer, List<Temperatures>> 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

你可以试试:

Map<Integer, ArrayList<Temperatures>> map = new HashMap<Integer, ArrayList<Temperatures>>(); //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<Integer, ArrayList<Temperatures>>> entry : map.entrySet()) 
{ 
    // entry.getKey() is the location 
    // entry.getValue() is the array of Temperatures objects with this location 
} 

请注意,我并没有实现,并尝试这个,但它可能工作或给你一个想法。

0

如果你想获取基于所有temperatures给定location你可以做这样的事情在的Java 8

public List<Temperatures> getTemperaturesFromLocation(List<Temperatures> temperatures, int location) { 
    return temperatures 
      .stream() 
      .filter(t -> 
       t.getLocation() == location 
      ) 
      .collect(Collectors.toList()); 
} 

或者定期循环/ if语句:

public List<Temperatures> getTemperaturesFromLocation(List<Temperatures> temperatures, int location) { 
    List<Temperatures> toReturn = new ArrayList<>(); 
    for(Temperatures temperature : temperatures) { 
     if(temperature.getLocation() == location) { 
      toReturn.add(temperature); 
     } 
    } 

    return toReturn; 
} 
1

您可以使用Java 8和流。

要过滤List使用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,其中关键是你的位置和值是Temperature与给定一个列表位置。