36

I have a Java Property file and there is a KEY as ORDER. So I retrieve the VALUE of that KEY using the getProperty() method after loading the property file like below.:

String s = prop.getProperty("ORDER");

then

s ="SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";

I need to create a HashMap from above string. SALES,SALE_PRODUCTS,EXPENSES,EXPENSES_ITEMS should be KEY of HashMap and 0,1,2,3, should be VALUEs of KEYs.

If it's hard corded, it seems like below:

Map<String, Integer> myMap  = new HashMap<String, Integer>();
myMap.put("SALES", 0);
myMap.put("SALE_PRODUCTS", 1);
myMap.put("EXPENSES", 2);
myMap.put("EXPENSES_ITEMS", 3);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Bishan
  • 15,211
  • 52
  • 164
  • 258
  • 2
    If it really is for the given String, keep the hardcoded solution... If not please tell us what you have tried so far and what your problem is. – pgras May 09 '12 at 10:47
  • http://mattgemmell.com/2008/12/08/what-have-you-tried/ – Denys Séguret May 09 '12 at 10:48
  • @pgras i have edited my post. i think now it's not complicated to understand. – Bishan May 09 '12 at 10:54
  • 1
    Does this answer your question? [Convert string representing key-value pairs to Map](https://stackoverflow.com/questions/14768171/convert-string-representing-key-value-pairs-to-map) – Volo Myhal Apr 07 '21 at 10:34

10 Answers10

70

You can do that with Guava's Splitter.MapSplitter:

Map<String, String> properties = Splitter.on(",")
    .withKeyValueSeparator(":")
    .split(inputString);
KARASZI István
  • 30,900
  • 8
  • 101
  • 128
55

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]));
}
Xavi López
  • 27,550
  • 11
  • 97
  • 161
30

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 !

Jeremy Bidet
  • 321
  • 3
  • 3
7

I recommend using com.fasterxml.jackson.databind.ObjectMapper (Maven repo link: https://mvnrepository.com/artifact/com.fasterxml.jackson.core) like

final ObjectMapper mapper = new ObjectMapper();
Map<String, Object> mapFromString = new HashMap<>();
try {
    mapFromString = mapper.readValue(theStringToParse, new TypeReference<Map<String, Object>>() {
        });
} catch (IOException e) {
    LOG.error("Exception launched while trying to parse String to Map.", e);
}
iusting
  • 7,850
  • 2
  • 22
  • 30
5

USING JAVA 8:

Map<String, String> headerMap = Arrays.stream(header.split(","))
                    .map(s -> s.split(":"))
                    .collect(Collectors.toMap(s -> s[0], s -> s[1]));
Chinmoy
  • 1,391
  • 13
  • 14
3

Assuming no key contains either ',' or ':':

Map<String, Integer> map = new HashMap<String, Integer>();
for(final String entry : s.split(",")) {
    final String[] parts = entry.split(":");
    assert(parts.length == 2) : "Invalid entry: " + entry;
    map.put(parts[0], new Integer(parts[1]));
}
Romain
  • 12,679
  • 3
  • 41
  • 54
3

You can also use JSONObject class from json.org to this will convert your HashMap to JSON string which is well formatted

Example:

Map<String,Object> map = new HashMap<>();
map.put("myNumber", 100);
map.put("myString", "String");

JSONObject json= new JSONObject(map);

String result= json.toString();

System.out.print(result);

result:

{'myNumber':100, 'myString':'String'}

Your can also get key from it like

System.out.print(json.get("myNumber"));

result:

100
2

Use StringTokenizer to parse the string.

String s ="SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
    Map<String, Integer> lMap=new HashMap<String, Integer>();


    StringTokenizer st=new StringTokenizer(s, ",");
    while(st.hasMoreTokens())
    {
        String [] array=st.nextToken().split(":");
        lMap.put(array[0], Integer.valueOf(array[1]));
    }
amicngh
  • 7,831
  • 3
  • 35
  • 54
1

You can to use split to do it:

 String[] elements = s.split(",");
 for(String s1: elements) {
     String[] keyValue = s1.split(":");
     myMap.put(keyValue[0], keyValue[1]);
 }

Nevertheless, myself I will go for guava based solution. https://stackoverflow.com/a/10514513/1356883

Community
  • 1
  • 1
kofemann
  • 4,217
  • 1
  • 34
  • 39
0

try

 String s = "SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
    HashMap<String,Integer> hm =new HashMap<String,Integer>();
    for(String s1:s.split(",")){
       String[] s2 = s1.split(":");
        hm.put(s2[0], Integer.parseInt(s2[1]));
    }
LyB8899
  • 313
  • 4
  • 14