I have a "Map<String, Object> values". How can I parse this map so that I get a following string at the end?
String string= "key1 = value1, key2 = value2, key3 = value3, ..."
It is important that as soon as a value contains a string then it should be provided with single quotes.
Thanks in advance
UPDATE 1
I need to expand my question.
So I need the string for a sql query. But the values which are strings have to be populated with SingleQuotes.
I show you my PostRequest method:
@Transactional
@PostMapping(value = "/config/test/{tableName}/{schemaName}")
public Map<String, Object> postValue(@RequestBody Map<String, Object> values, @PathVariable("tableName") String tableName,
@PathVariable("schemaName") String schemaName) {
String keyString = "";
String valueString = "";
Set<String> keySet = values.keySet();
for (String key : keySet) {
// add comma after first key-value pair only.
if (keyString.length() > 0) {
keyString = ",";
valueString = ",";
}
keyString = key;
Object valueObj = values.get(key);
if (valueObj instanceof String) {
valueString = valueString "'" valueObj.toString() "'";
;
} else if (valueObj instanceof Integer) {
Integer valueInt = (Integer) valueObj;
valueString = valueString valueInt;
} else if (valueObj instanceof Double) {
Double valueDouble = (Double) valueObj;
valueString = valueString valueDouble;
}
}
final String sql = "INSERT INTO " schemaName "." tableName "(" keyString ") VALUES(" valueString ")";
final Query query = em.createNativeQuery(sql);
query.executeUpdate();
return values;
}
Here I get 2 strings. One for the keys and one for the values.
But now I want to get only one string to change data in the database.
Here is my first try.
@Transactional
@PutMapping(value = "/config/test/{tableName}/{schemaName}/{id}")
public Map<String, Object> updateValue(@RequestBody Map<String, Object> values, @PathVariable("tableName") String tableName,
@PathVariable("schemaName") String schemaName, @PathVariable("id") String id) {
String keyString = "";
String valueString = "";
String updateString = "";
Set<String> keySet = values.keySet();
for (String key : keySet) {
if (keyString.length() > 0) {
keyString = "=";
updateString = ",";
}
updateString = key;
Object valueObj = values.get(key);
if (valueObj instanceof String) {
valueString = valueString "'" valueObj.toString() "'";
;
} else if (valueObj instanceof Integer) {
Integer valueInt = (Integer) valueObj;
valueString = valueString valueInt;
} else if (valueObj instanceof Double) {
Double valueDouble = (Double) valueObj;
valueString = valueString valueDouble;
}
}
final String sql = "UPDATE " schemaName "." tableName " SET " updateString " WHERE ID =" id;
final Query query = em.createNativeQuery(sql);
query.executeUpdate();
return values;
}
P.S. Yes I am using Spring Boot rather than Java, but I am trying to solve this without getting more dependencies.
CodePudding user response:
I just use Guava, probably toStringHelper can help with this, for example
System.out.println(MoreObjects.toStringHelper("className").add("name","hoyt").add("age",11).add("job","writeBugs")
.add("nullField", null)
.omitNullValues().toString());
// this is the print
// className{name=hoyt, age=11, job=writeBugs}
you can iter through the map, and call add method, the return of the add method is the Guava object itself, so you can chain it.
MoreObjects.toStringHelper tsh = MoreObjects.toStringHelper("className")
foreach(Entry e : map){
// add single quote if the value is a String,
Object value = e.getValue();
String valueString = value instanceof String?"'" value.toString() "'": value.toString();
tsh.add(e.getKey().toString(), valueString);
}
// System.out.println(tsh.toString())
CodePudding user response:
Refer the following example, you need to override the toString() Method
class TestObject {
int val;
public TestObject(int val){
this.val = val;
}
public String toString(){
return "" this.val;
}
}
Map<String, TestObject> map = new HashMap<>();
map.put("First Object", new TestObject(1));
map.put("Second Object", new TestObject(2));
map.put("Third Object", new TestObject(3));
map.toString() ==> {Third Object=3, First Object=1, Second Object=2} // on printing map object
Further you can edit map.toString() output as follows
map.toString().replace("{", "").replace("}", "");
CodePudding user response:
Stream based solution:
final Map<String, Object> values = Map.of("key1", "value1", "key2", "value2", "key3", "value3");
final var string = values.entrySet().stream().map(x -> x.getKey() " = " x.getValue()).collect(Collectors.joining(", "));
System.out.println(string); // key1 = value1, key2 = value2, key3 = value3
Or you can simply use StringBuilder
and iterate your Map
.
CodePudding user response:
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class ParseMap {
public static String getMapAsCustomString(Map<String, Object> map) {
return map.entrySet()
.stream()
.map(ParseMap::formatEntry)
.collect(Collectors.joining(", "));
}
public static String formatEntry(Entry<String, Object> entry) {
Object value = entry.getValue();
return entry.getKey() "=" (value instanceof String ? "'" value "'" : value.toString());
}
}
class Test {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", "Two");
map.put("key3", 7L);
String string = ParseMap.getMapAsCustomString(map);
System.out.println(string);
}
}