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?

3
  • trendyList should contain keys or values? Commented Dec 12, 2013 at 9:43
  • My Bad! It can only contain keys or values. However I am silly and I forgot this fact. Lorem ipsum dolor sit amet! Commented Dec 12, 2013 at 9:45
  • In what way is this question android specific? Commented Nov 10, 2016 at 9:06

2 Answers 2

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());
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.