Inflector provides an API for forming the plurals of nouns. Here's a simple example:
System.out.println(Noun.pluralOf("loaf"));
This will print
loaves
to the console.
It's handy to use Java 5 static imports to make this more readable, particularly if you are forming lots of plurals.
import static org.jvnet.inflector.Noun.pluralOf;
...
System.out.println(pluralOf("loaf"));
It is often useful to use a {@link java.util.Formatter}. For example,
System.out.printf("I bought 10 %s.", pluralOf("loaf"));
prints
I bought 10 loaves.
Of course, you can parameterize the number, as follows.
int n = 10;
System.out.printf("I bought %d %s.", n, pluralOf("loaf", n));
Notice that you pass the number into the pluralOf
method to make sure the noun agrees.
For example, if n = 1
in the previous example, it would correctly print
I bought 1 loaf.
The examples so far use the default locale to determine the pluralization algorithm to use. You can explictly set the locale to use by passing another argument:
System.out.println(pluralOf("pagnotta", Locale.ITALIAN));
prints
pagnotte
The pluralization algorithms that come with Inflector may not meet your needs. Perhaps there is no algorithm for your language, or perhaps the rules don't fit the usage that is appropriate for your application. The English pluralizer, for example, is fairly modern: it does not support many classical rules that are rare nowadays.
In this case it is straightforward to write your own pluralizer, or simply extend another one to override some of its rules. The follow code overrides the plural for box to boxen by using a {@link org.jvnet.inflector.rule.RegexReplacementRule}:
List<Rule> customRules = new ArrayList<Rule>();
customRules.add(new RegexReplacementRule("(?i)(.*)box", "$1boxen"));
Pluralizer customPluralizer = new RuleBasedPluralizer(customRules, Locale.ENGLISH, Noun.pluralizer(Locale.ENGLISH));
System.out.println(pluralOf("box"));
System.out.println(pluralOf("box", customPluralizer));
System.out.println(pluralOf("chatterbox", customPluralizer));
This prints
boxes
boxen
chatterboxen
If you are interested in writing more complex rules, there are many other implementations of {@link org.jvnet.inflector.Rule} in the {@link org.jvnet.inflector.rule} package.