TreeMap to ArrayList Java
Asked Answered
D

2

7

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?

Devil answered 12/12, 2013 at 9:41 Comment(3)
trendyList should contain keys or values?Gorski
My Bad! It can only contain keys or values. However I am silly and I forgot this fact. Lorem ipsum dolor sit amet!Devil
In what way is this question android specific?Intestate
P
16

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());
Parkerparkhurst answered 12/12, 2013 at 9:48 Comment(0)
M
2

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>

Masterly answered 12/12, 2013 at 9:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.