Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string array to hashmap [duplicate]

I have the following response

T2269|175@@2a1d2d89aa96ddd6|45464047

By using the split("\\|") i have converted into string array object. The meaning for the each field is as follows:

T2269                  id
175@@2a1d2d89aa96ddd6  cid
45464047               refno

No i have to convert it into HashMap object . Is their any solution for the above..

The above response is given for example. In real, the length of the string array object is 36.

like image 216
Daya Avatar asked Jul 05 '12 08:07

Daya


People also ask

How to make HashMap to allow duplicate keys?

You can't have duplicate keys in a Map . You can rather create a Map<Key, List<Value>> , or if you can, use Guava's Multimap . And then you can get the java.

Can map contain duplicate key?

Duplicate keys are not allowed in a Map.

How can we pass object of ArrayList into HashMap in Java?

To maintain the order, we can use LinkedHashMap which is the implementation of HashMap. Using ArrayList Iteration: Here, we just need to iterate on each of the elements of the ArrayList and the element can be converted into the key-value pair and store in the HashMap.


2 Answers

You have to loop and add the results one by one. Declare an array with the keys, something like:

static String[] keys = new String[]{"id", "cid", "refno", ...};

and then

String[] s = text.split("\\|");
for (int i = 0; i < s.length; i++)
  map.put(keys[i], s[i]);
like image 195
tibtof Avatar answered Nov 13 '22 10:11

tibtof


final String[] fields = input.split("\\|");
final Map<String, String> m = new HashMap<String, String>();
int i = 0;
for (String key : new String[] {"id", "cid", "refno"})
  m.put(key, fields[i++]);
like image 41
Marko Topolnik Avatar answered Nov 13 '22 11:11

Marko Topolnik