This can be done using the joining collector:
String str = map.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining(","));
Answer from Joe C on Stack OverflowThis can be done using the joining collector:
String str = map.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining(","));
Don't over complicate it:
String str = map.toString().replace(":", "=").replaceAll("^.|.$", "");
dictionary - Map to String in Java - Stack Overflow
java - Using lambda to format Map into String - Stack Overflow
java - How I can convert Map to String? - Stack Overflow
lambda - Java 8: How to convert String to Map<String,String>? - Stack Overflow
Use Object#toString().
String string = map.toString();
That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().
Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's
entrySetview's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as byString.valueOf(Object).
You can also use google-collections (guava) Joiner class if you want to customize the print format
Joiner.on(",").withKeyValueSeparator("=").join(map);
String formattedMap = params.entrySet().
stream()
.map(e -> "ctx._source." + e.getKey() + " = " + e.getValue())
.collect(Collectors.joining(","));
Try something like this:
Map<String, String> yourMap = /*...*/;
StringBuilder bob = new StringBuilder();
yourMap.forEach((key, value) -> bob.append(key).append("=").append(value).append(";"));
String result = bob.toString();
If necessary you could remove the last ; on result via String.concat().
Split the string by , to get individual map entries. Then split them by = to get the key and the value.
Map<String, String> reconstructedUtilMap = Arrays.stream(utilMapString.split(","))
.map(s -> s.split("="))
.collect(Collectors.toMap(s -> s[0], s -> s[1]));
Note: As pointed out by Andreas@ in the comments, this is not a reliable way to convert between a map and a string
EDIT: Thanks to Holger for this suggestion.
Use s.split("=", 2) to ensure that the array is never larger than two elements. This will be useful to not lose the contents (when the value has =)
Example: when the input string is "a=1,b=2,c=3=44=5555"
you will get {a=1, b=2, c=3=44=5555}
Earlier (just using s.split("=")) will give
{a=1, b=2, c=3}
Here is another option which streams a list of 1=1 etc. terms into a map.
String input = "1=1,2=2,3=3,4=4,5=5";
Map<String, String> map = Arrays.asList(input.split(",")).stream().collect(
Collectors.toMap(x -> x.replaceAll("=\\d+$", ""),
x -> x.replaceAll("^\\d+=", "")));
System.out.println(Collections.singletonList(map));
[{1=1, 2=2, 3=3, 4=4, 5=5}]
There is no need to reinvent the wheel. The Google Guava library provides the Splitter class.
Here's how you can use it along with some test code:
package com.sandbox;
import com.google.common.base.Splitter;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class SandboxTest {
@Test
public void testQuestionInput() {
Map<String, String> map = splitToMap("A=4 H=X PO=87");
assertEquals("4", map.get("A"));
assertEquals("X", map.get("H"));
assertEquals("87", map.get("PO"));
}
private Map<String, String> splitToMap(String in) {
return Splitter.on(" ").withKeyValueSeparator("=").split(in);
}
}
Java 8 to the rescue!
import static java.util.stream.Collectors.*;
Map<String, String> result = Arrays.stream(input.split(" "))
.map(s -> s.split("="))
.collect(Collectors.toMap(
a -> a[0], //key
a -> a[1] //value
));
NOTE: Assuming no duplicates. Otherwise look into the 3rd 'mergeFunction' argument.
I have to convert this
[(‘2’,’7’),(‘3’,’8’)] // array of dictionaries as a string in a text file
to a hashmap that will look like HashMap<String, String>().
for coverting my hashmap to a string I have this:
String mapAsString = map.keySet().stream()
.map(key -> key + "," + map.get(key))
.collect(Collectors.joining(", ", "(", ")"));But its not my exact output that I need.
How can I convert this back and forth in java using java lamba expressions?
Now that we have Java 8/streams, we can add one more possible answer to the list:
Assuming that each of the values actually are String objects, the cast to String should be safe. Otherwise some other mechanism for mapping the Objects to Strings may be used.
Map<String,Object> map = new HashMap<>();
Map<String,String> newMap = map.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));
If your Objects are containing of Strings only, then you can do it like this:
Map<String,Object> map = new HashMap<String,Object>(); //Object is containing String
Map<String,String> newMap =new HashMap<String,String>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if(entry.getValue() instanceof String){
newMap.put(entry.getKey(), (String) entry.getValue());
}
}
If every Objects are not String then you can replace (String) entry.getValue() into entry.getValue().toString().
Hi, the task is to assign every most populated city of each continent to its continent.
"countries" is the map type <String, Country> where String is the country code, and value is just the Country object assigned to that code.
same with "cities", but it's map type <Integer, City> where Integer is ID of the assigned city
The implementation I've made almost provides the solution but it's a map of <String, Optional<City>> instead of <String, City> (where String is the continent, and City is the most populated city)
How to convert the map values of type <Optional<City>> to type <City>?
Map<String, Optional<City>> ex = cities.values().stream()
.collect(Collectors.
groupingBy(p -> countries.get(p.getCountryCode()).getContinent(),
Collectors.maxBy(Comparator.comparing(City::getPopulation))));Also the github with exercises and provided data: https://github.com/deepcloudlabs/stream-api-exercises-part1
City class: https://github.com/deepcloudlabs/stream-api-exercises-part1/blob/master/src/com/example/domain/City.java
Country class: https://github.com/deepcloudlabs/stream-api-exercises-part1/blob/master/src/com/example/domain/Country.java
Well you can't safely cast it to a Map<String, String> because even though you know you've only got strings as the values, the compiler doesn't. That's like expecting:
Object x = "foo";
String y = x;
to work - it doesn't; you need to explicitly cast.
Likewise you can explicitly cast here, too, if you go via Object:
Map<String, Object> x = ...;
Map<String, String> y = (Map<String, String>) (Object) x;
Now you'll get a warning saying that it's an unchecked cast, because unlike the earlier "object to string" cast, there's no execution-time check that it's really valid. Type erasure means that a map doesn't really know its key/value types. So you end up with checking only being done when elements are fetched:
import java.util.*;
class Test {
public static void main(String[] args) {
Map<String, Object> x = new HashMap<>();
x.put("foo", "bar");
x.put("number", 0);
Map<String, String> y = (Map<String, String>) (Object) x;
// This is fine
System.out.println(y.get("foo"));
// This goes bang! It's trying to cast an Integer to a String
System.out.println(y.get("number"));
}
}
So if you really want to avoid creating a new map, this "cast via Object" will work - but it's far from ideal.
Your approach is safer, although you can make it slightly more efficient by avoiding the lookup:
public static Map<String, String> copyToStringValueMap(
Map<String, Object> input) {
Map<String, String> ret = new HashMap<>();
for (Map.Entry<String, Object> entry : input.entrySet()) {
ret.put(entry.getKey(), (String) entry.getValue());
}
return ret;
}
A Java 8 solution:
private Map<String, String> stringifyValues(Map<String, Object> variables) {
return variables.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> (String) e.getValue()));
}
So you can try like this
map<string,string> newMap= new Map<string,string>();
for(String strKey: mapValues.keyset())
{
newMap.put(strKey, String.valueof(mapValues.get(strKey)));
}
I have tried this worked for me:
enter code here
map<string,object> mspstrToObj = new Map<string,object>();
mspstrToObj.put('key1', 'obj1');
map<string,string> mspstrTostr = new Map<string,string>();
mspstrTostr.put('strKey1',string.valueof(mspstrToObj.get('key1')));
system.debug('=======mspstrTostr====='+mspstrTostr);
You need to create new Map and put the values as per above.