Java 计算ArrayList中对特定类型的引用数
假设我做了以下几点Java 计算ArrayList中对特定类型的引用数,java,arraylist,Java,Arraylist,假设我做了以下几点 ArrayList<Object> happylist = new ArrayList<Object>(); happylist.add("cat"); happylist.add(98); ... ArrayList happylist=new ArrayList(); happylist.add(“cat”); happylist.add(98); ... 等等,添加不同类型的元素。什么样的方法可以帮助我计算ArrayList中某个类型的引用次
ArrayList<Object> happylist = new ArrayList<Object>();
happylist.add("cat");
happylist.add(98);
...
ArrayList happylist=new ArrayList();
happylist.add(“cat”);
happylist.add(98);
...
等等,添加不同类型的元素。什么样的方法可以帮助我计算ArrayList中某个类型的引用次数 您可以使用
getClass()
方法来确定某个对象的类
请查看有关的文档 使用反射计算列表中不同类型参考的数量很容易。我编写了以下方法:
public Map<String, Integer> countReferences(List<Object> happyList) {
Map<String, Integer> referenceCounter = new HashMap<>();
for (Object object : happyList) {
String className = object.getClass().getName();
referenceCounter.put(className, referenceCounter.getOrDefault(className, 0) + 1);
}
return referenceCounter;
}
publicmap countReferences(列表happyList){
Map referenceCounter=new HashMap();
for(对象:happyList){
字符串className=object.getClass().getName();
referenceCounter.put(类名,referenceCounter.getOrDefault(类名,0)+1);
}
返回参考计数器;
}
基本上,每个名称不同的类都提供不同的引用。通过计算对每种类型的引用,并将它们存储在地图中,您就可以找到所需的内容
但我不太确定这些特殊问题的用处。在Java 8或其他高版本中,您可以使用流组API来完成,一个简单的代码如下:
ArrayList<Object> happylist = new ArrayList<Object>();
happylist.add("cat");
happylist.add(98);
happylist.add(198);
happylist.add(1L);
Map<Object,IntSummaryStatistics> result = happylist.stream()
.collect(Collectors.groupingBy(o -> o.getClass(),Collectors.summarizingInt(value -> 1)));
// output result
result.entrySet().stream()
.forEach(entry -> System.out.println(String.format("class name = %s\t sum count = %d",entry.getKey(),entry.getValue().getSum())));
ArrayList happylist=new ArrayList();
happylist.add(“cat”);
happylist.add(98);
happylist.add(198);
快乐列表。添加(1L);
映射结果=happylist.stream()
.collect(Collectors.groupingBy(o->o.getClass(),Collectors.summaringit(value->1));
//输出结果
result.entrySet().stream()
.forEach(entry->System.out.println(String.format(“类名=%s\t总和计数=%d”、entry.getKey()、entry.getValue().getSum()));
IntSummaryStatistics是用于收集统计信息(如计数、最小值、最大值、总和和平均值)的状态对象
谢谢你的回答,他们帮了很多忙。对于我在现实生活中遇到的特殊问题,我可以通过事先知道我要找的类型来缓解我的问题。在我的例子中,我使用以下方法来调用main方法
int counter = 0;
for (int i = 0; i < happylist.size(); i++) {
if (happylist.get(i) instanceof WantedType) {
counter++;
}
} return counter;
int计数器=0;
for(int i=0;i
int counter = 0;
for (int i = 0; i < happylist.size(); i++) {
if (happylist.get(i) instanceof WantedType) {
counter++;
}
} return counter;