String to HashMap JAVA
You can do that with Guava's Splitter.MapSplitter:
Map<String, String> properties = Splitter.on(",").withKeyValueSeparator(":").split(inputString);
Use the String.split()
method with the ,
separator to get the list of pairs. Iterate the pairs and use split()
again with the :
separator to get the key and value for each pair.
Map<String, Integer> myMap = new HashMap<String, Integer>();
String s = "SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
String[] pairs = s.split(",");
for (int i=0;i<pairs.length;i++) {
String pair = pairs[i];
String[] keyValue = pair.split(":");
myMap.put(keyValue[0], Integer.valueOf(keyValue[1]));
}
In one line :
HashMap<String, Integer> map = (HashMap<String, Integer>) Arrays.asList(str.split(",")).stream().map(s -> s.split(":")).collect(Collectors.toMap(e -> e[0], e -> Integer.parseInt(e[1])));
Details:
1) Split entry pairs and convert string array to List<String>
in order to use java.lang.Collection.Stream
API from Java 1.8
Arrays.asList(str.split(","))
2) Map the resulting string list "key:value"
to a string array with [0] as key and [1] as value
map(s -> s.split(":"))
3) Use collect
terminal method from stream API to mutate
collect(Collector<? super String, Object, Map<Object, Object>> collector)
4) Use the Collectors.toMap()
static method which take two Function to perform mutation from input type to key and value type.
toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)
where T is the input type, K the key type and U the value type.
5) Following lambda mutate String
to String
key and String
to Integer
value
toMap(e -> e[0], e -> Integer.parseInt(e[1]))
Enjoy the stream and lambda style with Java 8
. No more loops !