Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hashmap

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}]

like image 537
wishman Avatar asked May 05 '16 06:05

wishman


2 Answers

You just need to flatten the collection. In Java8:

    final Map<String, List<String>> adminErrorMap = ImmutableMap.of(
            "a", Lists.newArrayList("first", "second"),
            "b", Lists.newArrayList("third")
    );

    final List<String> results = adminErrorMap.values().stream()
            .flatMap(Collection::stream)
            .collect(Collectors.toList());

    results.forEach(System.out::println);

It prints:

first
second
third
like image 165
g-t Avatar answered Oct 23 '22 22:10

g-t


In Java8, you can use functional to do that:

adminErrorMap.values().forEach(adminValues::addAll);
like image 25
chengpohi Avatar answered Oct 23 '22 22:10

chengpohi