Search code examples
javaarraylistlinkedhashmap

Getting Data from Arraylist and input into put method of LinkedHashMap


i have this function below which takes in a arraylist of Strings and return a LinkedHashMap. I plan to use this linkedhashmap to write into a textfile subsequently.

    public Map<String,String> convertMap(ArrayList<String> Data){
    Map<String,String> myLinkedHashMap = new LinkedHashMap<String, String>();

    myLinkedHashMap.put("1", "first");
    myLinkedHashMap.put("2", "second");
    myLinkedHashMap.put("3", "third");

    return myLinkedHashMap;
    }

I am stucked on getting out the respective information from the ArrayList Data in order to use the put method to insert it into a linkedhashmap.

Lets say Arraylist Data contains: Name: John Age: 20 Gender: Male

I wan to replace 'Name' at the "1" Column , and 'John' at the "First" Column.

Can anyone kindly guide me on this issue ?


Solution

  • Let's say your ArrayList list contains:

    {"Name: John", "Age: 20", "Gender: Male"}
    

    You then could loop trough every element in your ArrayList to get every single string. You could then split the string into 2, then put both parts into your HashMap:

    for(String string : list) {
        String[] result = string.split(":", 2); // "Name: John"
        map.put(result[0], result[1].trim());   // becomes: "Name", "John"
    }
    

    I use trim() on the second String to remove any excess whitespaces.

    Note: This is not pretty. This only allows Strings in a certain format, but will do the job if they 100% are.