Java and how to deal with the singular plural form

One penny, two pence - adding an s to make it plural just won't cut it.

The singular plural variation is an annoyance that you’ve probably had to deal with many times.

public static String pluralizer(int count, String singular, String plural) {
    return (count==1) ? singular : plural;
}
Most times you can tackle the issue with something like this

So if you were populating a dashboard with users, you'd just call it like pluralizer("user", "users") and that would be it. But language is an irrational field, and I've recently stumbled across this answer on StackOverflow, that reflects the intrinsics of different languages. In this particular case, Czech.

// uživatel means user in Czech, 5 users has a particular form
1 uživatel
2 uživatelé
3 uživatelé
4 uživatelé
5 uživatelů
Czech Republic, the land of IntelliJ, looks pretty crazy!

Java 11 has a handy construct called ChoiceFormat that allows you to deal with this scenario in a very elegant way:

ChoiceFormat fmt = new ChoiceFormat("1#uživatel | 1.0< uživatelé | 4.0< uživatelů");
System.out.println(fmt.format(1)); // prints uživatel
System.out.println(fmt.format(4)); // prints uživatelé
System.out.println(fmt.format(5)); // prints uživatelů
The world is a messy place!
Plurals, by the camera of Geran de Klerk

There is another project that’s a worthy mention, Evo Inflector.

It's based on the work of Damian Conway – “An Algorithmic Approach to English Pluralization” – and does wonders for most forms of the English language. But it’s an external dependency, more than often will be overkill and only covers ~70% of the words.

Link to Oracle’s ChoiceFormat documentation.


The problem above reminds me of CODE by Charles Petzold. If you can, I highly suggest you add it to your read-list. Dwells with the intricacies of all codes, written, spoken, drawn and, obviously, compiled.