Search code examples
javahashmap

How to convert Values in a Hashmap to a List<String>


I have a Hashmap of type

Map<String, List<String>> adminErrorMap = new HashMap<>();

I want to be able to iterate thru the entire hashmap and get all the values to a single List<String>. The Keys are irrelevant.

I have done something like this:

List<String> adminValues = new ArrayList<>();

for (Map.Entry<String, List<String>> entry : adminErrorMap.entrySet()) {                
         adminValues.add(entry.getValue().toString());
    }
System.out.println(adminValues);

Output

[[{description=File Path, value=PurchaseOrder.plsql}, {description=Component, value=PURCH}, {description=Commit Date, value=Thu May 05 00:32:01 IST 2016}],[{description=File Path, value=CustomerOrder.plsql}, {description=Component, value=COMP}, {description=Commit Date, value=Thu June 05 00:32:01 IST 2016}]]

As you can see, there are [] inside a main [].

How to have all values inside one []. Like shown below;

Or is there any other way to implement this?

[{description=File Path, value=PurchaseOrder.plsql}, {description=Component, value=PURCH}, {description=Commit Date, value=Thu May 05 00:32:01 IST 2016},{description=File Path, value=CustomerOrder.plsql}, {description=Component, value=COMP}, {description=Commit Date, value=Thu June 05 00:32:01 IST 2016}]


Solution

  • Use addAll instead of add, in order to add all the Strings of all the List<String>s to a single List<String> :

    for (List<String> value : adminErrorMap.values())   
    {                
         adminValues.addAll(value);
    }