Backend Development 4 min read

Utility Class for Counting Occurrences in Java/Groovy Using JSONObject

This article presents a reusable Java/Groovy utility class that leverages JSONObject's containKey method to count occurrences of values, offering multiple overloaded count methods for single objects, lists, and list elements, along with example code and usage notes.

FunTester
FunTester
FunTester
Utility Class for Counting Occurrences in Java/Groovy Using JSONObject

During testing of a lottery activity, the author needed a way to tally each draw result and compare it with expected values, finding traditional switch‑case approaches cumbersome; instead, they created a utility class that uses the JSONObject containsKey method to increment counts or insert new entries.

The provided code defines a CountTool class with several static count methods:

static def count(JSONObject counts, Object object) – increments the count for a single object with a default increment of 1.

static def count(JSONObject counts, Object object, int num) – increments the count using a specified default value.

static def count(List list, def str) – returns the number of times a specific element appears in a list.

static def count(List list) – groups list elements, sorts them, and outputs each element with its occurrence count.

The implementation relies on counts.put(object, Integer.valueOf(counts.getOrDefault(object.toString(), num))) and Java streams for grouping and sorting.

Note: The approach uses toString() , which works for basic types and strings; for other objects it may produce hash codes, so additional handling or method overloading may be required.
backendJavaUtilityJSONObjectCounting
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.