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}
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}]
Convert String array to Map using Java 8 Lambda expressions - Stack Overflow
Collect list of strings to map with Java 8 Stream API - Stack Overflow
collections - How to convert String into Hashmap in java - Stack Overflow
java - List of String to Map Java8 - Stack Overflow
You can use IntStream to get this thing done. Use the integer value as the key, and the relevant value in the string array at that index as the value of the map.
Map<Integer, String> counterToStr = IntStream.range(0, strings.length)
.boxed()
.collect(Collectors.toMap(Function.identity(), i -> strings[i]));
Another alternative that obviates the need of split would be,
Map<Integer, String> counterToStr = IntStream.range(0, strings.length)
.boxed()
.collect(Collectors.toMap(Function.identity(), i -> str.charAt(i) + ""));
You can write like
String str = "abcd";
Map<Integer, Character> map = IntStream.range(0, str.length()).boxed()
.collect(Collectors.toMap(Function.identity(), pos -> str.charAt(pos)));
No need to split the String with String[] strings = str.split(""); A simple one-liner.
You were almost correct with groupingBy, but the second parameter of that is a Collector, not a Function. Thus I used toMap.
Map<String, Integer> map = Stream.of("bla", "blabla", "blablabla").distinct()
.collect(Collectors.toMap(Function.identity(), String::length));
You don't have to do something so complicated. Here is an example code:
...
...
List<String> ll= // the list of words that you have.
Map<String,Integer> map = new HashMap<>();// or any other kind of map you want to create
for(String s:ll){
map.put(s,s.length());
}
Now you have a map that satisfies your requirement.
This is one solution. If you want to make it more generic, you can use the StringUtils library.
String value = "{first_name = naresh,last_name = kumar,gender = male}";
value = value.substring(1, value.length()-1); //remove curly brackets
String[] keyValuePairs = value.split(","); //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();
for(String pair : keyValuePairs) //iterate over the pairs
{
String[] entry = pair.split("="); //split the pairs to get key and value
map.put(entry[0].trim(), entry[1].trim()); //add them to the hashmap and trim whitespaces
}
For example you can switch
value = value.substring(1, value.length()-1);
to
value = StringUtils.substringBetween(value, "{", "}");
if you are using StringUtils which is contained in apache.commons.lang package.
In a single line you can convert any type of object to any other type of object.
(Since I use Gson quite liberally, I am sharing a Gson based approach)
Gson gson = new Gson();
Map<Object,Object> attributes = gson.fromJson(gson.toJson(value),Map.class);
What it does is:
gson.toJson(value)will serialize your object into its equivalent Json representation.gson.fromJsonwill convert the Json string to specified object. (in this example -Map)
There are 2 advantages with this approach:
- The flexibility to pass any Object instead of String to
toJsonmethod. - You can use this single line to convert to any object even your own declared objects.
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.
Given a String, I want to create a hashmap that maps a Character to the number of times it shows up in the string.
I saw in Stack Overflow the following line:
Map<String, Long> map =
Arrays.stream(s1.split("")).
collect(Collectors.groupingBy(c -> c, Collectors.counting()));
And it works great, but it maps a String to the counter.
I tried writing it for Characters, and as far as I understood, there isn't a char stream, and I'll have to use IntStream. So I converted it to an IntStream, and used the same Collectors function.
Map<Integer, Long> map =
s1.chars().
collect(Collectors.groupingBy(c -> c, Collectors.counting()));
The above doesn't work. The error is:
Error:(14, 27) java: method collect in interface java.util.stream.IntStream cannot be applied to given types;
required: java.util.function.Supplier<R>,java.util.function.ObjIntConsumer<R>,java.util.function.BiConsumer<R,R>
found: java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.Map<java.lang.Object,java.lang.Long>>
reason: cannot infer type-variable(s) R
(actual and formal argument lists differ in length)
What is the difference between the two?