Code, JavaEE

Flatten Map Utility


import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 *
 * @author david.king
 */
public class FreemarkerResponseUtil {
 public FreemarkerResponseUtil() {}

 /**
 * This method unpacks nested maps and nested lists and
 * moves its data in to the top-level map returned
 * @param map
 * @return
 */
 public Map<String, Object> flattenMap(Map<String, Object> map) {
 Map<String, Object> redata = new HashMap<>();

Iterator iterator = map.entrySet().iterator();

while (iterator.hasNext()) {

Map.Entry<String, Object> entry = (Map.Entry<String, Object>)iterator.next();

String key = entry.getKey();
 Object val = entry.getValue();

if (val instanceof Map) {
 redata.putAll((Map<String, Object>) val);
 } else if (val instanceof Integer) {
 val = String.valueOf(val);
 redata.put(key, val.toString());
 } else if (val instanceof Double) {
 val = String.valueOf(val);
 redata.put(key, val.toString());
 } else if (val instanceof Boolean) {
 val = String.valueOf(((Boolean) val).booleanValue());
 redata.put(key, val.toString());
 } else if (val == true) {
 val = String.valueOf(Boolean.TRUE);
 redata.put(key, val.toString());
 } else if (val instanceof List) {
 // Need to check for a List<Map<String, Object>> as well !!!
 for (Object item : (List<String>)val) {
 if (item instanceof Map) {
 redata.putAll((Map<String, Object>) item);
 } else {
 redata.put(captialize(item.toString()), item);
 }
 }
 }
 else {
 redata.put(key, val.toString());
 }

}

return redata;
 }

 private String captialize(String element) {
 return element.substring(0, 1).toUpperCase() + element.substring(1);
 }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s