Reputation: 105
Let's say I've made the following.
ArrayList<Object> happylist = new ArrayList<Object>();
happylist.add("cat");
happylist.add(98);
...
And so on, adding different types of elements. What sort of method would help me count how many times there was a reference to certain type in my ArrayList?
Upvotes: 3
Views: 156
Reputation: 105
Thank you for your answers, they helped a lot. For my particular problem in real life, I was able to ease my problem by knowing beforehand what type I was looking for. In my case, I did the following method to call in main method.
int counter = 0;
for (int i = 0; i < happylist.size(); i++) {
if (happylist.get(i) instanceof WantedType) {
counter++;
}
} return counter;
Upvotes: 0
Reputation: 1430
In Java 8 or other high version you can use Stream Group API to do, a simple code like this:
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())));
IntSummaryStatistics is state object for collecting statistics such as count, min, max, sum, and average.
Upvotes: 0
Reputation: 2392
It could easily be done counting the number of different types of reference in the list using reflections. I have coded the following method:
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;
}
Basically, each class with difference name gives difference reference. By counting reference to each type, and storing them in map gives you what you are looking for.
But I am not quite sure the usefulness of such particular problems.
Upvotes: 1
Reputation: 364
static long countByTypeJava8(Collection col, Class clazz) {
return col.stream()
.filter(clazz::isInstance)
.count();
}
static long countByType(Collection col, Class clazz) {
long count = 0;
for (Object o : col) {
if (clazz.isInstance(o)) {
count++;
}
}
return count;
}
Upvotes: 0