Effective way to handle singular/plural word based on some collection size

This gets complicated in languages other than English, that inflector aims to support in the future.

I am familiar with Czech where user = uživatel and:

1 uživatel
2 uživatelé
3 uživatelé
4 uživatelé
5 uživatelů

...

You can see why programs written with hardcoded singular+plural would get un-i18n-able.


Edit:
Java11 allows you to use the following:

ChoiceFormat fmt = new ChoiceFormat("1#uživatel | 1.0< uživatelé | 4< uživatelů");
System.out.println(fmt.format(1));
System.out.println(fmt.format(4));
System.out.println(fmt.format(5));

ChoiceFormat documentation


Take a look at inflector, a java project which lets you do Noun.pluralOf("user"), or Noun.pluralOf("user", userList.size()), and which handles a bunch of variations and unusual cases (person->people, loaf->loaves, etc.), as well as letting you define custom mapping rules when necessary.


Hmm, I don't quite see why you need a library for this. I would think the function to do it is trivial:

public String singlePlural(int count, String singular, String plural)
{
  return count==1 ? singular : plural;
}

Calls would look like:

singlePlural(count, "user", "users");
singlePlural(count, "baby", "babies");
singlePlural(count, "person", "people");
singlePlural(count, "cherub", "cherubim");
... etc ...

Maybe this library does a whole bunch of other things that make it useful. I suppose you could say that it supplies a dictionary of what all the plural forms are, but in any given program you don't care about the plurals of all the words in the language, just the ones you are using in this program. I guess if the word that could be singular or plural is not known at compile time, if it's something entered by the user, then I'd want a third party dictionary rather than trying to build one myself.

Edit

Suddenly it occurs to me that what you were looking for was a function for making plurals generically, embodying a set of rules like "normally just add 's', but if the word ends in 'y' change the 'y' to 'ies', if it ends in 's' change it to 'ses', ..." etc. I think in English that would be impossible for any practical purpose: there are too many special cases, like "person/people" and "child/children" etc. I think the best you could do would be to have a generic "add an 's'" rule, maybe a few other common cases, and then a long list of exceptions. Perhaps in other languages one could come up with a fairly simple rule.

So as I say, if the word is not known at compile time but comes from some user input, then yes, a third-party dictionary is highly desirable.

Tags:

Java

Jsp

Jsp Tags