Showing posts with label Message Formatting. Show all posts
Showing posts with label Message Formatting. Show all posts

Friday, 20 May 2016

Java Message Format Using Named Placeholder

The Java MessageFormat class allows user to pre-define a string with placeholders and then fill the placeholders with actual strings later to construct a proper message.

It's all fine if you're used to numbered placeholders e.g. {0} and {1}.

Apache Commons has a StrSubstitutor class which allows use of named placeholders.
Although StrSubstitutor is a bit more verbose, but it helps when you're handling lots of key/value pairs.


import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.text.StrSubstitutor;

public class MessagePlaceHolder {
     
      public static void main(String[] args) {
            Map<String,String> map = new HashMap<String, String>();
            map.put("name", "Rajesh");
            map.put("email", "rkdixit3@gmail.com");
           
            String format = "Hello {name}, your email is {email}.";
            String message = StrSubstitutor.replace(format,map,"{","}");
            System.out.println(message);
      }
}

Output:
Hello Rajesh, your email is rkdixit3@gmail.com.

Monday, 22 February 2016

How to format messages in Java?

MessageFormat

The MessageFormat class can be used quite nicely to compose messages.

MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

import java.text.*;

public class MessageFormator {

     public static void main(String[] args) {
           String message="Request id# {0} will be resolve till {1}.";
           Object values[] = { "1325", "25-Mar-2016" };
           String s = MessageFormat.format(message, values);
           System.out.println(s);
    }
}
Output:
Request id# 1325 will be resolve till 25-Mar-2016.







Related Posts Plugin for WordPress, Blogger...