TreeMap to ArrayList Java

User3 picture User3 · Dec 12, 2013 · Viewed 15.8k times · Source

I have a TreeMap which has a string key and the value part is a List with atleast four values.

Map<String,List<String>> mMap = new TreeMap<String,List<String>>(); 

I am using the tree map so that my keys are sorted. However after the sort I want to map this TreeMap to a listview. I want to convert the Map to a list and then build an Adapter for listview. However I am not able to convert it when I do

ArrayList<String> trendyList = new ArrayList<String>(mMap);  

It says: The constructor ArrayList<String>(Map<String,List<String>>) is undefined

Is there any other way I can do this?

Answer

Tim B picture Tim B · Dec 12, 2013

Assuming you want a list of list of strings:

List<List<String>> trendyList = new ArrayList<>(mMap.values()); 

If you want to merge the lists then it becomes a bit more complex, you would need to run through the values yourself and do the merge.

To merge the lists:

List<String> trendyList = new ArrayList<>(); 
for (List<String> s: mMap.values()) {
   trendyList.addAll(s);
}

To merge the lists with keys:

List<String> trendyList = new ArrayList<>(); 
for (Entry<String, List<String>> e: mMap.entrySet()) {
   trendyList.add(e.getKey());
   trendyList.addAll(e.getValue());
}

In Java 8 you get new tools for doing this.

To merge the lists:

// Flat map replaces one item in the stream with multiple items
List<String> trendyList = mMap.values().stream().flatMap(List::stream).collect(Collectors.toList())

To merge the lists with keys:

List<String> trendyList = mMap.entrySet().stream().flatMap(e->Stream.concat(Stream.of(e.getKey()), e.getValue().stream()).collect(Collectors.toList());