Converting string array to hashmap [duplicate]

泄露秘密 提交于 2019-12-04 07:16:57
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++]);

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]);

The key should be unique, so obviously using the ID as a key would make perfect sense, and the value you can store as an array/list containing the id,cid,refno, or you can create an object containing thos fields and store it.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!