Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there alternatives to String.format that use cached formatting? [closed]

Are there any alternatives to Java's String.format which can cache the format String insead of requiring a format parse on each run? it would probably look something like this

Formatter formatter = new Formatter( "oh %s" );

formatter.format("my"); // oh my
like image 638
xenoterracide Avatar asked Jan 07 '15 18:01

xenoterracide


People also ask

What is Composite formatting?

A composite format string consists of zero or more runs of fixed text intermixed with one or more format items. The fixed text is any string that you choose, and each format item corresponds to an object or boxed structure in the list.

What is a composite string?

A composite string is basically a record defined by an IOLIST statement consisting of variables and associated formats used to create the string. Assigning data to a composite string causes the elements defined in the IOList to be loaded with their associated values.

Is string format slow Java?

Avoid using String. format() when possible. It is slow and difficult to read when you have more than two variables.


2 Answers

You could use the MessageFormat class.

MessageFormat mf = new MessageFormat("oh {0}");
System.out.println(mf.format(new Object[] {"my"}));
System.out.println(mf.format(new Object[] {"this will do it!"}));

Output:

oh my
oh this will do it!
like image 113
rgettman Avatar answered Oct 17 '22 05:10

rgettman


You could look into MessageFormat you can create one instance for a pattern and use it like this:

MessageFormat messageFormat = new MessageFormat(pattern); // initialize once
messageFormat.format(arguments, new StringBuffer(), null).toString(); // use often
like image 5
Leonard Brünings Avatar answered Oct 17 '22 07:10

Leonard Brünings