Changing HashMap keys during iteration - java

is it possible to change keys of a the same HashMap instance during iteration ? Because map entry set don't have a method entry.setKey(). Now what I can think off is create another HashMap...
MultipartParsingResult parsingResult = parseRequest(request);
Map<String, String[]> mpParams = parsingResult.getMultipartParameters();
Map<String, String[]> mpParams2 = new HashMap<String, String[]>();
Iterator<Entry<String,String[]>> it = mpParams.entrySet().iterator();
while (it.hasNext()) {
Entry<String,String[]> entry = it.next();
String name = entry.getKey();
if (name.startsWith(portletNamespace)) {
mpParams2.put(name.substring(portletNamespace.length(), name.length()), entry.getValue());
}
else {
mpParams2.put(name, entry.getValue());
}
}

Maybe this helps:
map.put(newkey,map.remove(oldkey));

You should keep information in other collection to modify it after iteration. You can only remove entry using iterator.remove() during iterator. HashMap contract forbids mutating it during iteration.

There are four common types of modification you might want to do to the keys or values in a HashMap.
To change a HashMap key, you look up the value object with get, then remove the old key and put it with the new key.
To change the fields in a value object, look the value object up by key with get, then use its setter methods.
To replace the value object in its entirely, just put a new value object at the old key.
To replace the value object with one based on the old, look the value object up with get, create a new object, copy data over from the old one, then put the new object under the same key.
Something like this example.
static class Food
{
// ------------------------------ FIELDS ------------------------------
String colour;
String name;
float caloriesPerGram;
// -------------------------- PUBLIC INSTANCE METHODS --------------------------
public float getCaloriesPerGram()
{
return caloriesPerGram;
}
public void setCaloriesPerGram( final float caloriesPerGram )
{
this.caloriesPerGram = caloriesPerGram;
}
public String getColour()
{
return colour;
}
public void setColour( final String colour )
{
this.colour = colour;
}
public String getName()
{
return name;
}
public void setName( final String name )
{
this.name = name;
}
public String toString()
{
return name + " : " + colour + " : " + caloriesPerGram;
}
// --------------------------- CONSTRUCTORS ---------------------------
Food( final String name, final String colour, final float caloriesPerGram )
{
this.name = name;
this.colour = colour;
this.caloriesPerGram = caloriesPerGram;
}
}
// --------------------------- main() method ---------------------------
/**
* Sample code to TEST HashMap Modifying
*
* #param args not used
*/
public static void main( String[] args )
{
// create a new HashMap
HashMap<String, Food> h = new HashMap<String, Food>( 149
/* capacity */,
0.75f
/* loadfactor */ );
// add some Food objecs to the HashMap
// see http://www.calorie-charts.net for calories/gram
h.put( "sugar", new Food( "sugar", "white", 4.5f ) );
h.put( "alchol", new Food( "alcohol", "clear", 7.0f ) );
h.put( "cheddar", new Food( "cheddar", "orange", 4.03f ) );
h.put( "peas", new Food( "peas", "green", .81f ) );
h.put( "salmon", new Food( "salmon", "pink", 2.16f ) );
// (1) modify the alcohol key to fix the spelling error in the key.
Food alc = h.get( "alchol" );
h.put( "alcohol", alc );
h.remove( "alchol" );
// (2) modify the value object for sugar key.
Food sug = h.get( "sugar" );
sug.setColour( "brown" );
// do not need to put.
// (3) replace the value object for the cheddar key
// don't need to get the old value first.
h.put( "cheddar", new Food( "cheddar", "white", 4.02f ) );
// (4) replace the value object for the peas key with object based on previous
Food peas = h.get( "peas" );
h.put( "peas", new Food( peas.getName(), peas.getColour(), peas.getCaloriesPerGram() * 1.05f ) );
// enumerate all the keys in the HashMap in random order
for ( String key : h.keySet() )
{
out.println( key + " = " + h.get( key ).toString() );
}
}// end main
}
I hope this helps

i got to this thread when i needed to change the keys of the map entries.
in my case i have a JSON representation in a Map , meaning it can hold map or list of maps, here is the code:
private Map<String,Object> changeKeyMap(Map<String, Object> jsonAsMap) throws InterruptedException {
Map<String,Object> mapClone = new LinkedHashMap<>();
for (Map.Entry<String, Object> entry : jsonAsMap.entrySet()) {
if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
Object value = entry.getValue();
if (entry.getValue() instanceof Map) {
value = changeKeyMap((Map) entry.getValue());
} else if (isListOfMaps(entry.getValue())) {
value = changeKeyListOfMaps((List<Map<String, Object>>) entry.getValue());
}
String changedKey = changeSingleKey(entry.getKey());
mapClone.put(changedKey, value);
}
return mapClone;
}
private List<Map<String,Object>> changeKeyListOfMaps(List<Map<String,Object>> listOfMaps) throws InterruptedException {
List<Map<String,Object>> newInnerMapList = new ArrayList<>();
for(Object singleMapFromArray :listOfMaps){
Map<String,Object> changeKeyedMap = changeKeyMap((Map<String, Object>) singleMapFromArray);
newInnerMapList.add(changeKeyedMap);
}
return newInnerMapList;
}
private boolean isListOfMaps(Object object) {
return object instanceof List && !((List) object).isEmpty() && ((List) object).get(0) instanceof Map;
}
private String changeSingleKey(String originalKey) {
return originalKey + "SomeChange"
}

The best thing to do is to copy the map into a new one with the modifications you want, then return this new maps and destroy the old one.
I wonder what's the performance impact of this solution however.

Related

How to access an object attribute from a String in Java?

I have a String that tells me what attribute I should use to make some filtering. How can I use this String to actually access the data in the object ?
I have a method that returns a List of strings telling me how to filter my List of objects. Such as:
String[] { "id=123", "name=foo" }
So my first idea was to split the String into 2 parts with:
filterString.split("=") and use the first part of the String (e.g. "id") to identify the attribute being filtered.
Coming for a JS background, I would do it like this:
const attr = filterString.split('=')[0]; // grabs the "id" part from the string "id=123", for example
const filteredValue = filterString.split('=')[1]; // grabs the "123" part from the string "id=123", for example
items.filter(el => el[`${attr}`] === filteredValue) // returns an array with the items where the id == "123"
How would I be able to do that with Java ?
You can use reflections to get fields of class by dynamic name.
#Test
void test() throws NoSuchFieldException, IllegalAccessException {
String[] filters = {"id=123", "name=foo"};
List<Item> list = newArrayList(new Item(123, "abc"), new Item(2, "foo"), new Item(123, "foo"));
Class<Item> itemClass = Item.class;
for (String filter : filters) {
String key = StringUtils.substringBefore(filter, "=");
String value = StringUtils.substringAfter(filter, "=");
Iterator<Item> iterator = list.iterator();
while (iterator.hasNext()) {
Item item = iterator.next();
Field field = itemClass.getDeclaredField(key);
field.setAccessible(true);
Object itemValue = field.get(item);
if (!value.equals(String.valueOf(itemValue))) {
iterator.remove();
}
}
}
assertEquals(1, list.size());
}
But I agree with comment from sp00m - it's slow and potentially dangerous.
This code should work :
//create the filter map
Map<String, String> expectedFieldValueMap = new HashMap<>();
for (String currentDataValue : input) {
String[] keyValue = currentDataValue.split("=");
String expectedField = keyValue[0];
String expectedValue = keyValue[1];
expectedFieldValueMap.put(expectedField, expectedValue);
}
Then iterate over input object list ( have used Employee class with id and name fields & prepared a test data list with few Employee objects called inputEmployeeList which is being iterated ) and see if all filters passes, using reflection, though slow, is one way:
for (Employee e : inputEmployeeList) {
try {
boolean filterPassed = true;
for (String expectedField : expectedFieldValueMap.keySet()) {
String expectedValue = expectedFieldValueMap.get(expectedField);
Field fieldData = e.getClass().getDeclaredField(expectedField);
fieldData.setAccessible(true);
if (!expectedValue.equals(fieldData.get(e))) {
filterPassed = false;
break;
}
}
if (filterPassed) {
System.out.println(e + " object passed the filter");
}
} catch (Exception any) {
any.printStackTrace();
// handle
}
}

How to Loop next element in hashmap

I have a set of strings like this
A_2007-04, A_2007-09, A_Agent, A_Daily, A_Execute, A_Exec, B_Action, B_HealthCheck
I want output as:
Key = A, Value = [2007-04,2007-09,Agent,Execute,Exec]
Key = B, Value = [Action,HealthCheck]
I'm using HashMap to do this
pckg:{A,B}
count:total no of strings
reports:set of strings
Logic I used is nested loop:
for (String l : reports[i]) {
for (String r : pckg) {
String[] g = l.split("_");
if (g[0].equalsIgnoreCase(r)) {
report.add(g[1]);
dirFiles.put(g[0], report);
} else {
break;
}
}
}
I'm getting output as
Key = A, Value = [2007-04,2007-09,Agent,Execute,Exec]
How to get second key?
Can someone suggest logic for this?
Assuming that you use Java 8, it can be done using computeIfAbsent to initialize the List of values when it is a new key as next:
List<String> tokens = Arrays.asList(
"A_2007-04", "A_2007-09", "A_Agent", "A_Daily", "A_Execute",
"A_Exec", "P_Action", "P_HealthCheck"
);
Map<String, List<String>> map = new HashMap<>();
for (String token : tokens) {
String[] g = token.split("_");
map.computeIfAbsent(g[0], key -> new ArrayList<>()).add(g[1]);
}
In terms of raw code this should do what I think you are trying to achieve:
// Create a collection of String any way you like, but for testing
// I've simply split a flat string into an array.
String flatString = "A_2007-04,A_2007-09,A_Agent,A_Daily,A_Execute,A_Exec,"
+ "P_Action,P_HealthCheck";
String[] reports = flatString.split(",");
Map<String, List<String>> mapFromReportKeyToValues = new HashMap<>();
for (String report : reports) {
int underscoreIndex = report.indexOf("_");
String key = report.substring(0, underscoreIndex);
String newValue = report.substring(underscoreIndex + 1);
List<String> existingValues = mapFromReportKeyToValues.get(key);
if (existingValues == null) {
// This key hasn't been seen before, so create a new list
// to contain values which belong under this key.
existingValues = new ArrayList<>();
mapFromReportKeyToValues.put(key, existingValues);
}
existingValues.add(newValue);
}
System.out.println("Generated map:\n" + mapFromReportKeyToValues);
Though I recommend tidying it up and organising it into a method or methods as fits your project code.
Doing this with Map<String, ArrayList<String>> will be another good approach I think:
String reports[] = {"A_2007-04", "A_2007-09", "A_Agent", "A_Daily",
"A_Execute", "A_Exec", "P_Action", "P_HealthCheck"};
Map<String, ArrayList<String>> map = new HashMap<>();
for (String rep : reports) {
String s[] = rep.split("_");
String prefix = s[0], suffix = s[1];
ArrayList<String> list = new ArrayList<>();
if (map.containsKey(prefix)) {
list = map.get(prefix);
}
list.add(suffix);
map.put(prefix, list);
}
// Print
for (Map.Entry<String, ArrayList<String>> entry : map.entrySet()) {
String key = entry.getKey();
ArrayList<String> valueList = entry.getValue();
System.out.println(key + " " + valueList);
}
for (String l : reports[i]) {
String[] g = l.split("_");
for (String r : pckg) {
if (g[0].equalsIgnoreCase(r)) {
report = dirFiles.get(g[0]);
if(report == null){ report = new ArrayList<String>(); } //create new report
report.add(g[1]);
dirFiles.put(g[0], report);
}
}
}
Removed the else part of the if condition. You are using break there which exits the inner loop and you never get to evaluate the keys beyond first key.
Added checking for existing values. As suggested by Orin2005.
Also I have moved the statement String[] g = l.split("_"); outside inner loop so that it doesn't get executed multiple times.

Remove HashMap Key from String

I have mobile numbers in database table column, in a format of country_code followed by mobile_number
So Mobile Number format is like this,
+91123456789 // country code of India is +91 followed by mobile number
+97188888888 // Country code of UAE +971
I have one HashMap containing CountryCodes of 5 countries like this,
map.put("+91","India")
map.put("+94","Sri Lanka")
map.put("+881","Bangladesh")
map.put("+971","UAE")
map.put("+977","Nepal")
My Bean Structure is something like this
class UserDetails {
// other fields
String countryCode;
String mobileNumber;
}
Now my task is to take the mobile number from Database table column and split it in two parts and set countryCode and mobileNumber, but country code length(in map's key) varies between 3 and 4. This checking can be done by using subString() and equals() but I don't think it's correct way, So what would be the elegant(may be checking in map key) way to solve this issue?
Although there is a library which seems to already do the trick, I think I'd go for an easy self-written solution:
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class CountryExtractor {
private static final Map<String, String> COUNTRY_MAPPING = new HashMap<>();
static {
COUNTRY_MAPPING.put("+91", "India");
COUNTRY_MAPPING.put("+94", "Sri Lanka");
COUNTRY_MAPPING.put("+881", "Bangladesh");
COUNTRY_MAPPING.put("+971", "UAE");
COUNTRY_MAPPING.put("+977", "Nepal");
}
public static void main(String[] args) {
String[] inputs = new String[] { "+91123456789", "+97188888888" };
for (String input : inputs) {
System.out.println(Arrays.toString(parseNumber(input)));
}
}
private static String[] parseNumber(String number) {
for (String countryCode : COUNTRY_MAPPING.keySet()) {
if (number.startsWith(countryCode)) {
return new String[] { countryCode, number.replace(countryCode, "") };
}
}
return new String[0];
}
}
Output:
[+91, 123456789]
[+971, 88888888]
Note that this may not work correctly when a mobile prefix is a substring of another, but according to Wikipedia country calling codes are prefix codes and therefore guarantee that "there is no whole code word in the system that is a prefix (initial segment) of any other code word in the system".
IMHO a single map is better. An example;
public static void main(String args[]) throws Exception {
Map<String, String> map = new HashMap<>();
put(map, "+91", "India");
put(map, "+94", "Sri Lanka");
put(map, "+881", "Bangladesh");
put(map, "+971", "UAE");
put(map, "+977", "Nepal");
map = Collections.unmodifiableMap(map);
String mobileNumber = "+91123456789";
System.out.println(countryCode(map.keySet(), mobileNumber));
}
private static void put(Map<String, String> map, String key, String value) {
if (countryCode(map.keySet(), key) != null) {
throw new IllegalArgumentException("...");
}
map.put(key, value);
}
public static String countryCode(Set<String> countryCodes, String number) {
if (number == null || number.length() < 3) {
throw new IllegalArgumentException("...");
}
String code = number.substring(0, 3);
if (!countryCodes.contains(code)) {
if (number.length() > 3) {
code = number.substring(0, 4);
if (!countryCodes.contains(code)) {
code = null;
}
} else {
code = null;
}
}
return code;
}
You could use two maps for country code of different lengths and then search first for a match with 3 letters, and then with 4 letters.
HashMap<String, String > threeLetterCodes = new HashMap<String, String>();
threeLetterCodes.put("+91","India");
threeLetterCodes.put("+94","Sri Lanka");
HashMap<String, String > fourLetterCodes = new HashMap<String, String>();
fourLetterCodes.put("+881","Bangladesh");
fourLetterCodes.put("+971","UAE");
fourLetterCodes.put("+977","Nepal");
String test = "+97188888888";
String prefix = test.substring(0, 3);
String country = threeLetterCodes.get(prefix);
if (country == null) {
prefix = test.substring(0, 4);
country = fourLetterCodes.get(prefix);
}
System.out.println(country);
Output:
UAE

multiple HashMap implementation

I am trying to implement the use of two HashMaps and it seems to be more or less successful also.But now my problem is i want to update the value of a hashMap based on a check.ie if userId is already existing in the hash i need to update the timestamp corresponding to it...
Below given is my code.How can we accomplish the updation of values .Can that be done usiong setValue..?but how..?please help me friends..
public static void main(String[] args)
{
HashMap sessionTimeStampHash = new HashMap<Long, Long>(); //sessionID is the key and timeStamp is the value
//userID is the key and sessionTimeStampHash object is the value
HashMap<String, HashMap<Long, Long>> userSessionHash = new HashMap<String, HashMap<Long, Long>>();
sessionTimeStampHash.put("sessionID", "timeStamp");
userSessionHash.put("userID", sessionTimeStampHash);
// System.out.println(userSessionHash);
sessionTimeStampHash = new HashMap();
sessionTimeStampHash.put("sessionID1", "timeStamp1");
userSessionHash.put("userID1", sessionTimeStampHash);
// System.out.println(userSessionHash);
sessionTimeStampHash = new HashMap();
sessionTimeStampHash.put("sessionID2", "timeStamp2");
userSessionHash.put("userID2", sessionTimeStampHash);
// System.out.println(userSessionHash);
sessionTimeStampHash = new HashMap();
sessionTimeStampHash.put("sessionID3", "timeStamp3");
userSessionHash.put("userID3", sessionTimeStampHash);
// System.out.println(userSessionHash);
for (Entry<String, HashMap<Long, Long>> entry : userSessionHash.entrySet())
{
String key = entry.getKey();
System.out.println(key);
System.out.println(entry.getValue());
String userId = "userID3";
if (key.equals(userId))
{
System.out.println("Check Successful");
String TimeStamp = newTime;
entry.setValue() // how can i change my timeStamp
}
}
}
You can do without for loop
if(userSessionHash.get(userId)!=null)
userSessionHash.get(userId).put(userSessionHash.get(userId).keySet().toArray[0], timestamp);
Loop on your second map (I assume you want to update all the sessionIds for the user) and modify the value.
if (key.equals(userId))
{
System.out.println("Check Successful");
String TimeStamp=newTime;
for ( String sessionId : entry.getValue().keySet() )
{
entry.put(sessionid, timeStamp);
}
}
String userId = "userID3";
Long timeStamp = userSessionHash.containsKey(userId) ? userSessionHash.get(userSessionHash) : 0;
userSessionHash.put(userId,new AtomicLong(request.getSession(false).getMaxInactiveInterval()))

Named placeholders in string formatting

In Python, when formatting string, I can fill placeholders by name rather than by position, like that:
print "There's an incorrect value '%(value)s' in column # %(column)d" % \
{ 'value': x, 'column': y }
I wonder if that is possible in Java (hopefully, without external libraries)?
StrSubstitutor of jakarta commons lang is a light weight way of doing this provided your values are already formatted correctly.
http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/text/StrSubstitutor.html
Map<String, String> values = new HashMap<String, String>();
values.put("value", x);
values.put("column", y);
StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
String result = sub.replace("There's an incorrect value '%(value)' in column # %(column)");
The above results in:
"There's an incorrect value '1' in column # 2"
When using Maven you can add this dependency to your pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
not quite, but you can use MessageFormat to reference one value multiple times:
MessageFormat.format("There's an incorrect value \"{0}\" in column # {1}", x, y);
The above can be done with String.format() as well, but I find messageFormat syntax cleaner if you need to build complex expressions, plus you dont need to care about the type of the object you are putting into the string
Another example of Apache Common StringSubstitutor for simple named placeholder.
String template = "Welcome to {theWorld}. My name is {myName}.";
Map<String, String> values = new HashMap<>();
values.put("theWorld", "Stackoverflow");
values.put("myName", "Thanos");
String message = StringSubstitutor.replace(template, values, "{", "}");
System.out.println(message);
// Welcome to Stackoverflow. My name is Thanos.
You can use StringTemplate library, it offers what you want and much more.
import org.antlr.stringtemplate.*;
final StringTemplate hello = new StringTemplate("Hello, $name$");
hello.setAttribute("name", "World");
System.out.println(hello.toString());
public static String format(String format, Map<String, Object> values) {
StringBuilder formatter = new StringBuilder(format);
List<Object> valueList = new ArrayList<Object>();
Matcher matcher = Pattern.compile("\\$\\{(\\w+)}").matcher(format);
while (matcher.find()) {
String key = matcher.group(1);
String formatKey = String.format("${%s}", key);
int index = formatter.indexOf(formatKey);
if (index != -1) {
formatter.replace(index, index + formatKey.length(), "%s");
valueList.add(values.get(key));
}
}
return String.format(formatter.toString(), valueList.toArray());
}
Example:
String format = "My name is ${1}. ${0} ${1}.";
Map<String, Object> values = new HashMap<String, Object>();
values.put("0", "James");
values.put("1", "Bond");
System.out.println(format(format, values)); // My name is Bond. James Bond.
Thanks for all your help! Using all your clues, I've written routine to do exactly what I want -- python-like string formatting using dictionary. Since I'm Java newbie, any hints are appreciated.
public static String dictFormat(String format, Hashtable<String, Object> values) {
StringBuilder convFormat = new StringBuilder(format);
Enumeration<String> keys = values.keys();
ArrayList valueList = new ArrayList();
int currentPos = 1;
while (keys.hasMoreElements()) {
String key = keys.nextElement(),
formatKey = "%(" + key + ")",
formatPos = "%" + Integer.toString(currentPos) + "$";
int index = -1;
while ((index = convFormat.indexOf(formatKey, index)) != -1) {
convFormat.replace(index, index + formatKey.length(), formatPos);
index += formatPos.length();
}
valueList.add(values.get(key));
++currentPos;
}
return String.format(convFormat.toString(), valueList.toArray());
}
This is an old thread, but just for the record, you could also use Java 8 style, like this:
public static String replaceParams(Map<String, String> hashMap, String template) {
return hashMap.entrySet().stream().reduce(template, (s, e) -> s.replace("%(" + e.getKey() + ")", e.getValue()),
(s, s2) -> s);
}
Usage:
public static void main(String[] args) {
final HashMap<String, String> hashMap = new HashMap<String, String>() {
{
put("foo", "foo1");
put("bar", "bar1");
put("car", "BMW");
put("truck", "MAN");
}
};
String res = replaceParams(hashMap, "This is '%(foo)' and '%(foo)', but also '%(bar)' '%(bar)' indeed.");
System.out.println(res);
System.out.println(replaceParams(hashMap, "This is '%(car)' and '%(foo)', but also '%(bar)' '%(bar)' indeed."));
System.out.println(replaceParams(hashMap, "This is '%(car)' and '%(truck)', but also '%(foo)' '%(bar)' + '%(truck)' indeed."));
}
The output will be:
This is 'foo1' and 'foo1', but also 'bar1' 'bar1' indeed.
This is 'BMW' and 'foo1', but also 'bar1' 'bar1' indeed.
This is 'BMW' and 'MAN', but also 'foo1' 'bar1' + 'MAN' indeed.
Apache Commons StringSubstitutor can be used. Note that StrSubstitutor is deprecated.
import org.apache.commons.text.StringSubstitutor;
// ...
Map<String, String> values = new HashMap<>();
values.put("animal", "quick brown fox");
values.put("target", "lazy dog");
StringSubstitutor sub = new StringSubstitutor(values);
String result = sub.replace("The ${animal} jumped over the ${target}.");
// "The quick brown fox jumped over the lazy dog."
This class supports providing default values for variables.
String result = sub.replace("The number is ${undefined.property:-42}.");
// "The number is 42."
To use recursive variable replacement, call setEnableSubstitutionInVariables(true);.
Map<String, String> values = new HashMap<>();
values.put("b", "c");
values.put("ac", "Test");
StringSubstitutor sub = new StringSubstitutor(values);
sub.setEnableSubstitutionInVariables(true);
String result = sub.replace("${a${b}}");
// "Test"
I am the author of a small library that does exactly what you want:
Student student = new Student("Andrei", 30, "Male");
String studStr = template("#{id}\tName: #{st.getName}, Age: #{st.getAge}, Gender: #{st.getGender}")
.arg("id", 10)
.arg("st", student)
.format();
System.out.println(studStr);
Or you can chain the arguments:
String result = template("#{x} + #{y} = #{z}")
.args("x", 5, "y", 10, "z", 15)
.format();
System.out.println(result);
// Output: "5 + 10 = 15"
There is nothing built into Java at the moment of writing this. I would suggest writing your own implementation. My preference is for a simple fluent builder interface instead of creating a map and passing it to function -- you end up with a nice contiguous chunk of code, for example:
String result = new TemplatedStringBuilder("My name is {{name}} and I from {{town}}")
.replace("name", "John Doe")
.replace("town", "Sydney")
.finish();
Here is a simple implementation:
class TemplatedStringBuilder {
private final static String TEMPLATE_START_TOKEN = "{{";
private final static String TEMPLATE_CLOSE_TOKEN = "}}";
private final String template;
private final Map<String, String> parameters = new HashMap<>();
public TemplatedStringBuilder(String template) {
if (template == null) throw new NullPointerException();
this.template = template;
}
public TemplatedStringBuilder replace(String key, String value){
parameters.put(key, value);
return this;
}
public String finish(){
StringBuilder result = new StringBuilder();
int startIndex = 0;
while (startIndex < template.length()){
int openIndex = template.indexOf(TEMPLATE_START_TOKEN, startIndex);
if (openIndex < 0){
result.append(template.substring(startIndex));
break;
}
int closeIndex = template.indexOf(TEMPLATE_CLOSE_TOKEN, openIndex);
if(closeIndex < 0){
result.append(template.substring(startIndex));
break;
}
String key = template.substring(openIndex + TEMPLATE_START_TOKEN.length(), closeIndex);
if (!parameters.containsKey(key)) throw new RuntimeException("missing value for key: " + key);
result.append(template.substring(startIndex, openIndex));
result.append(parameters.get(key));
startIndex = closeIndex + TEMPLATE_CLOSE_TOKEN.length();
}
return result.toString();
}
}
Apache Commons Lang's replaceEach method may come in handy dependeding on your specific needs. You can easily use it to replace placeholders by name with this single method call:
StringUtils.replaceEach("There's an incorrect value '%(value)' in column # %(column)",
new String[] { "%(value)", "%(column)" }, new String[] { x, y });
Given some input text, this will replace all occurrences of the placeholders in the first string array with the corresponding values in the second one.
You should have a look at the official ICU4J library. It provides a MessageFormat class similar to the one available with the JDK but this former supports named placeholders.
Unlike other solutions provided on this page. ICU4j is part of the ICU project that is maintained by IBM and regularly updated. In addition, it supports advanced use cases such as pluralization and much more.
Here is a code example:
MessageFormat messageFormat =
new MessageFormat("Publication written by {author}.");
Map<String, String> args = Map.of("author", "John Doe");
System.out.println(messageFormat.format(args));
As of 2022 the up-to-date solution is Apache Commons Text StringSubstitutor
From the doc:
// Build map
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target} ${undefined.number:-1234567890} times.";
// Build StringSubstitutor
StringSubstitutor sub = new StringSubstitutor(valuesMap);
// Replace
String resolvedString = sub.replace(templateString)
;
You could have something like this on a string helper class
/**
* An interpreter for strings with named placeholders.
*
* For example given the string "hello %(myName)" and the map <code>
* <p>Map<String, Object> map = new HashMap<String, Object>();</p>
* <p>map.put("myName", "world");</p>
* </code>
*
* the call {#code format("hello %(myName)", map)} returns "hello world"
*
* It replaces every occurrence of a named placeholder with its given value
* in the map. If there is a named place holder which is not found in the
* map then the string will retain that placeholder. Likewise, if there is
* an entry in the map that does not have its respective placeholder, it is
* ignored.
*
* #param str
* string to format
* #param values
* to replace
* #return formatted string
*/
public static String format(String str, Map<String, Object> values) {
StringBuilder builder = new StringBuilder(str);
for (Entry<String, Object> entry : values.entrySet()) {
int start;
String pattern = "%(" + entry.getKey() + ")";
String value = entry.getValue().toString();
// Replace every occurence of %(key) with value
while ((start = builder.indexOf(pattern)) != -1) {
builder.replace(start, start + pattern.length(), value);
}
}
return builder.toString();
}
Based on the answer I created MapBuilder class:
public class MapBuilder {
public static Map<String, Object> build(Object... data) {
Map<String, Object> result = new LinkedHashMap<>();
if (data.length % 2 != 0) {
throw new IllegalArgumentException("Odd number of arguments");
}
String key = null;
Integer step = -1;
for (Object value : data) {
step++;
switch (step % 2) {
case 0:
if (value == null) {
throw new IllegalArgumentException("Null key value");
}
key = (String) value;
continue;
case 1:
result.put(key, value);
break;
}
}
return result;
}
}
then I created class StringFormat for String formatting:
public final class StringFormat {
public static String format(String format, Object... args) {
Map<String, Object> values = MapBuilder.build(args);
for (Map.Entry<String, Object> entry : values.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
format = format.replace("$" + key, value.toString());
}
return format;
}
}
which you could use like that:
String bookingDate = StringFormat.format("From $startDate to $endDate"),
"$startDate", formattedStartDate,
"$endDate", formattedEndDate
);
I created also a util/helper class (using jdk 8) which can format a string an replaces occurrences of variables.
For this purpose I used the Matchers "appendReplacement" method which does all the substitution and loops only over the affected parts of a format string.
The helper class isn't currently well javadoc documented. I will changes this in the future ;)
Anyway I commented the most important lines (I hope).
public class FormatHelper {
//Prefix and suffix for the enclosing variable name in the format string.
//Replace the default values with any you need.
public static final String DEFAULT_PREFIX = "${";
public static final String DEFAULT_SUFFIX = "}";
//Define dynamic function what happens if a key is not found.
//Replace the defualt exception with any "unchecked" exception type you need or any other behavior.
public static final BiFunction<String, String, String> DEFAULT_NO_KEY_FUNCTION =
(fullMatch, variableName) -> {
throw new RuntimeException(String.format("Key: %s for variable %s not found.",
variableName,
fullMatch));
};
private final Pattern variablePattern;
private final Map<String, String> values;
private final BiFunction<String, String, String> noKeyFunction;
private final String prefix;
private final String suffix;
public FormatHelper(Map<String, String> values) {
this(DEFAULT_NO_KEY_FUNCTION, values);
}
public FormatHelper(
BiFunction<String, String, String> noKeyFunction, Map<String, String> values) {
this(DEFAULT_PREFIX, DEFAULT_SUFFIX, noKeyFunction, values);
}
public FormatHelper(String prefix, String suffix, Map<String, String> values) {
this(prefix, suffix, DEFAULT_NO_KEY_FUNCTION, values);
}
public FormatHelper(
String prefix,
String suffix,
BiFunction<String, String, String> noKeyFunction,
Map<String, String> values) {
this.prefix = prefix;
this.suffix = suffix;
this.values = values;
this.noKeyFunction = noKeyFunction;
//Create the Pattern and quote the prefix and suffix so that the regex don't interpret special chars.
//The variable name is a "\w+" in an extra capture group.
variablePattern = Pattern.compile(Pattern.quote(prefix) + "(\\w+)" + Pattern.quote(suffix));
}
public static String format(CharSequence format, Map<String, String> values) {
return new FormatHelper(values).format(format);
}
public static String format(
CharSequence format,
BiFunction<String, String, String> noKeyFunction,
Map<String, String> values) {
return new FormatHelper(noKeyFunction, values).format(format);
}
public static String format(
String prefix, String suffix, CharSequence format, Map<String, String> values) {
return new FormatHelper(prefix, suffix, values).format(format);
}
public static String format(
String prefix,
String suffix,
BiFunction<String, String, String> noKeyFunction,
CharSequence format,
Map<String, String> values) {
return new FormatHelper(prefix, suffix, noKeyFunction, values).format(format);
}
public String format(CharSequence format) {
//Create matcher based on the init pattern for variable names.
Matcher matcher = variablePattern.matcher(format);
//This buffer will hold all parts of the formatted finished string.
StringBuffer formatBuffer = new StringBuffer();
//loop while the matcher finds another variable (prefix -> name <- suffix) match
while (matcher.find()) {
//The root capture group with the full match e.g ${variableName}
String fullMatch = matcher.group();
//The capture group for the variable name resulting from "(\w+)" e.g. variableName
String variableName = matcher.group(1);
//Get the value in our Map so the Key is the used variable name in our "format" string. The associated value will replace the variable.
//If key is missing (absent) call the noKeyFunction with parameters "fullMatch" and "variableName" else return the value.
String value = values.computeIfAbsent(variableName, key -> noKeyFunction.apply(fullMatch, key));
//Escape the Map value because the "appendReplacement" method interprets the $ and \ as special chars.
String escapedValue = Matcher.quoteReplacement(value);
//The "appendReplacement" method replaces the current "full" match (e.g. ${variableName}) with the value from the "values" Map.
//The replaced part of the "format" string is appended to the StringBuffer "formatBuffer".
matcher.appendReplacement(formatBuffer, escapedValue);
}
//The "appendTail" method appends the last part of the "format" String which has no regex match.
//That means if e.g. our "format" string has no matches the whole untouched "format" string is appended to the StringBuffer "formatBuffer".
//Further more the method return the buffer.
return matcher.appendTail(formatBuffer)
.toString();
}
public String getPrefix() {
return prefix;
}
public String getSuffix() {
return suffix;
}
public Map<String, String> getValues() {
return values;
}
}
You can create a class instance for a specific Map with values (or suffix prefix or noKeyFunction)
like:
Map<String, String> values = new HashMap<>();
values.put("firstName", "Peter");
values.put("lastName", "Parker");
FormatHelper formatHelper = new FormatHelper(values);
formatHelper.format("${firstName} ${lastName} is Spiderman!");
// Result: "Peter Parker is Spiderman!"
// Next format:
formatHelper.format("Does ${firstName} ${lastName} works as photographer?");
//Result: "Does Peter Parker works as photographer?"
Further more you can define what happens if a key in the values Map is missing (works in both ways e.g. wrong variable name in format string or missing key in Map).
The default behavior is an thrown unchecked exception (unchecked because I use the default jdk8 Function which cant handle checked exceptions) like:
Map<String, String> map = new HashMap<>();
map.put("firstName", "Peter");
map.put("lastName", "Parker");
FormatHelper formatHelper = new FormatHelper(map);
formatHelper.format("${missingName} ${lastName} is Spiderman!");
//Result: RuntimeException: Key: missingName for variable ${missingName} not found.
You can define a custom behavior in the constructor call like:
Map<String, String> values = new HashMap<>();
values.put("firstName", "Peter");
values.put("lastName", "Parker");
FormatHelper formatHelper = new FormatHelper(fullMatch, variableName) -> variableName.equals("missingName") ? "John": "SOMETHING_WRONG", values);
formatHelper.format("${missingName} ${lastName} is Spiderman!");
// Result: "John Parker is Spiderman!"
or delegate it back to the default no key behavior:
...
FormatHelper formatHelper = new FormatHelper((fullMatch, variableName) -> variableName.equals("missingName") ? "John" :
FormatHelper.DEFAULT_NO_KEY_FUNCTION.apply(fullMatch,
variableName), map);
...
For better handling there are also static method representations like:
Map<String, String> values = new HashMap<>();
values.put("firstName", "Peter");
values.put("lastName", "Parker");
FormatHelper.format("${firstName} ${lastName} is Spiderman!", map);
// Result: "Peter Parker is Spiderman!"
There is Java Plugin to use string interpolation in Java (like in Kotlin, JavaScript). Supports Java 8, 9, 10, 11…​ https://github.com/antkorwin/better-strings
Using variables in string literals:
int a = 3;
int b = 4;
System.out.println("${a} + ${b} = ${a+b}");
Using expressions:
int a = 3;
int b = 4;
System.out.println("pow = ${a * a}");
System.out.println("flag = ${a > b ? true : false}");
Using functions:
#Test
void functionCall() {
System.out.println("fact(5) = ${factorial(5)}");
}
long factorial(int n) {
long fact = 1;
for (int i = 2; i <= n; i++) {
fact = fact * i;
}
return fact;
}
For more info, please read the project README.
The quick answer is no, unfortunately. However, you can come pretty close to a reasonable syntaks:
"""
You are $compliment!
"""
.replace('$compliment', 'awesome');
It's more readable and predictable than String.format, at least!
My answer is to:
a) use StringBuilder when possible
b) keep (in any form: integer is the best, speciall char like dollar macro etc) position of "placeholder" and then use StringBuilder.insert() (few versions of arguments).
Using external libraries seems overkill and I belive degrade performance significant, when StringBuilder is converted to String internally.
Try Freemarker, templating library.
I tried in just a quick way
public static void main(String[] args)
{
String rowString = "replace the value ${var1} with ${var2}";
Map<String,String> mappedValues = new HashMap<>();
mappedValues.put("var1", "Value 1");
mappedValues.put("var2", "Value 2");
System.out.println(replaceOccurence(rowString, mappedValues));
}
private static String replaceOccurence(String baseStr ,Map<String,String> mappedValues)
{
for(String key :mappedValues.keySet())
{
baseStr = baseStr.replace("${"+key+"}", mappedValues.get(key));
}
return baseStr;
}
I ended up with the next solution:
Create class TemplateSubstitutor with method substitute() and use it to format output
Then create a string template and fill it with values
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String template = "WRR = {WRR}, SRR = {SRR}\n" +
"char_F1 = {char_F1}, word_F1 = {word_F1}\n";
Map<String, Object> values = new HashMap<>();
values.put("WRR", 99.9);
values.put("SRR", 99.8);
values.put("char_F1", 80);
values.put("word_F1", 70);
String message = TemplateSubstitutor.substitute(values, template);
System.out.println(message);
}
}
class TemplateSubstitutor {
public static String substitute(Map<String, Object> map, String input_str) {
String output_str = input_str;
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
output_str = output_str.replace("{" + key + "}", String.valueOf(value));
}
return output_str;
}
}
https://dzone.com/articles/java-string-format-examples String.format(inputString, [listOfParams]) would be the easiest way. Placeholders in string can be defined by order. For more details check the provided link.

Categories