Listing Objects that share the same attribute
本问题已经有最佳答案,请猛点这里访问。
好的,所以基本上我尝试迭代
1 | private ArrayList<Temperatures> recordedTemperature; |
并显示每个共享相同"位置"的人。位置是在temperatures类的构造函数中初始化的int变量:
1 2 3 4 5 6 | public Temperatures(int location, int day, double temperature) { this.location = location; this.day = day; this.temperature = temperature; } |
我如何迭代温度数组列表中的所有对象,找出那些具有匹配位置属性的对象并返回它们?
可以使用Java 8和流。
要过滤
1 | List<Temperature> filtered = recordedTemperature.stream().filter(t -> t.getLocation() == 1).collect(Collectors.toList()); |
按位置分组使用collect和groupingby
1 | Map<Integer, List<Temperature>> grouped = recordedTemperature.stream().collect(Collectors.groupingBy(Temperature::getLocation)); |
您将得到
如果您试图根据给定的EDCOX1(1)来获取所有EDCOX1×0,那么您可以在Java 8中这样做:
1 2 3 4 5 6 7 8 | public List<Temperatures> getTemperaturesFromLocation(List<Temperatures> temperatures, int location) { return temperatures .stream() .filter(t -> t.getLocation() == location ) .collect(Collectors.toList()); } |
或者使用正则循环/if语句:
1 2 3 4 5 6 7 8 9 10 | 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 2 3 4 5 6 7 | 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 } |
然后迭代这些映射以获取所有组:
1 2 3 4 5 |
请注意,我没有实现并尝试这个方法,但它可能会起作用,或者给您一个想法。
您需要遍历您的列表,并根据您的条件验证列表中的每个项目。在您的情况下,需要传递列表并标识所有唯一的位置(例如,将它们放在地图中),并为每个位置添加具有该位置的条目列表。
1 2 3 4 5 6 | 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 } |