0

Please, help me convert a HashMap<String, ArrayList<String>> to HashMap <String, String>, where each ArrayList should be converted into one String that contains the ArrayList's elments.

7
  • 1
    What would "the one String" look like? Commented Jun 22, 2013 at 20:19
  • I want send this HashMap to the session and display using jstl. Commented Jun 22, 2013 at 20:19
  • 4
    You need to specify how exactly you want to convert data in ArrayList<String> to String (some example showing input and result would be nice) and also what part of your code doesn't work as you expect (you have some code right?) Commented Jun 22, 2013 at 20:20
  • 2
    Why don't you just call toString on the entire Map? That should fulfill your requirements. Commented Jun 22, 2013 at 20:22
  • 1
    @haraldK Huh? That would convert the Map to a String, where OP wants to convert to a Map<String,String>. Steve P. has a correct response. (Hmm, just noted OP's comment about jstl, so maybe he does want a big String and not a Map<String, String> Commented Jun 22, 2013 at 20:44

1 Answer 1

3

I believe that this is what you are looking for.

//HashMap<String, ArrayList<String>> hashMap;  
//initialized somewhere above

HashMap<String, String> newHashMap = new HashMap<>();

for (Map.Entry<String, ArrayList<String>> entry : hashMap.entrySet())
{
    newHashMap.put(entry.getKey(), entry.getValue().toString());
}

Not sure if your issue was with toString() or how to iterate over a HashMap, if it was the latter, here's how to iterate over a map.

Here's a from-start-to-finish example:

    ArrayList<String> al = new ArrayList<>();
    al.add("The");
    al.add("End");

    HashMap<String, ArrayList<String>> hashMap = new HashMap<>();
    hashMap.put("This is", al);

    HashMap<String, String> newHashMap = new HashMap<>();

    for (Map.Entry<String, ArrayList<String>> entry : hashMap.entrySet())
    {
        newHashMap.put(entry.getKey(), entry.getValue().toString());
    }

    System.out.println(newHashMap.toString());
    //prints {This is=[The, End]}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.