简体   繁体   中英

Java Complex Collection

I have data in this format: (in a file)

key1:fieldname1:fieldvalue1
key1:fieldname2:fieldvalue2
key2:fieldname1:fieldvalue1

I need this to be formatted to:

{key1=[{fieldname1=fieldvalue1,fieldname2=fieldvalue2}],key2=[{fieldname1=fieldvalue1}]}

As you can see it involves Map and ArrayList. I actually need it in Map and ArrayList.

Please suggest.

Thank you

Find string method "split" and how to use it and also how to read text file line by line. By this, you can easily parse line by line and get what key, fieldname and fieldvalue is.

Then you can go as following for each line:

  1. If key does not exist in your map, create empty array in it.

  2. Add item to array specified at given key

Try this:

    String[] str = {"key1:fieldname1:fieldvalue1", "key1:fieldname2:fieldvalue2", "key2:fieldname1:fieldvalue1"};
    Map<String, List<String>> map = new HashMap<String, List<String>>();

    for (String s: str) {
        String[] temp = s.split(":");

        if (map.get(temp[0]) == null) {
            map.put(temp[0], new ArrayList());
        }
        map.get(temp[0]).add(temp[1] + "=" + temp[2]);
    }

This example is under the assumption that fieldname1:fieldvalue2 need to be stored as string. You can get the high level idea and then modify according to your requirements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM