Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeMap to ArrayList Java

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?

like image 727
User3 Avatar asked Dec 12 '13 09:12

User3


2 Answers

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());
like image 59
Tim B Avatar answered Nov 16 '22 16:11

Tim B


A Map can be seen as a colleciton of key-value pairs, a list is just a collection of values. You have to choose if you now want your keys, then you use keySet() or if you want your values than you use values() wich returns a collection of List<String>

like image 36
Jens Baitinger Avatar answered Nov 16 '22 14:11

Jens Baitinger