要按字段计算出现次数,可以使用HashMap来统计每个字段的出现次数。以下是一个示例代码:
import android.util.Pair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CountOccurrences {
public static void main(String[] args) {
List>> list = new ArrayList<>();
list.add(new Pair<>(1L, new Pair<>(1, 1)));
list.add(new Pair<>(2L, new Pair<>(1, 2)));
list.add(new Pair<>(3L, new Pair<>(2, 1)));
list.add(new Pair<>(4L, new Pair<>(2, 2)));
list.add(new Pair<>(5L, new Pair<>(1, 1)));
Map longOccurrences = new HashMap<>();
Map, Integer> pairOccurrences = new HashMap<>();
for (Pair> pair : list) {
// 计算Long字段的出现次数
Long key = pair.first;
if (longOccurrences.containsKey(key)) {
longOccurrences.put(key, longOccurrences.get(key) + 1);
} else {
longOccurrences.put(key, 1);
}
// 计算Pair字段的出现次数
Pair pairKey = pair.second;
if (pairOccurrences.containsKey(pairKey)) {
pairOccurrences.put(pairKey, pairOccurrences.get(pairKey) + 1);
} else {
pairOccurrences.put(pairKey, 1);
}
}
// 打印结果
System.out.println("Long字段的出现次数:");
for (Map.Entry entry : longOccurrences.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println("Pair字段的出现次数:");
for (Map.Entry, Integer> entry : pairOccurrences.entrySet()) {
System.out.println(entry.getKey().first + ", " + entry.getKey().second + ": " + entry.getValue());
}
}
}
这个示例代码中,我们定义了一个List,其中每个元素是一个Pair
注意:这个示例代码是Java代码,可以在Android项目中使用。只需将该代码放入合适的位置,并适配到你的实际需求。