Joe
Joe

Reputation: 23

Add varied number of parameters to properties file

suppose we are trying to print out a list of names of children that go to school using a properties file and the list of names varies in size:

List<String> names = newArrayList<>("john", "sarah", "george");

the properties file is:

key.print.names = "{0} all go to {1} school"

I want an output like:

john, sarah, and george all go to MLK school

Keep in mind the list of names will change. How can that be done with a properties file?

Upvotes: 1

Views: 859

Answers (1)

Renato
Renato

Reputation: 2157

You can simple use

MessageFormat.format(property.getString("key.print.names"),String.join(",",names),schoolName);

EDIT: how to add and before last name:

String listOfNames = String.join(" and ",
                        Arrays.asList(
                            String.join(",", names.subList(0, names.size() - 1)), 
                            names.get(names.size() - 1)
                        )
                     );
MessageFormat.format(property.getString("key.print.names"),listOfNames,schoolName);

EDIT: as suggested in the comment, if you want a sort of localization you can use a property for the conjunction and the snippet will become:

String listOfNames = String.join(new StringBuilder(" ")              
                                .append(property.getString("key.conjunction.en"))
                                .append(" ").toString(),
                        Arrays.asList(
                            String.join(",", names.subList(0, names.size() - 1)), 
                            names.get(names.size() - 1)
                        )
                     );
MessageFormat.format(property.getString("key.print.names"),listOfNames,schoolName);

In a more complex scenario (web application) you can use ResourceBoundle, more info here and here

Upvotes: 1

Related Questions