Search code examples
androidarraylisttreemap

Split TreeMap<List<>,List<>> into two ArrayList


i have two ArrayLists:

List<String> names = new ArrayList<String>(10);
List<Drawable> drawables = new ArrayList<Drawable>(10);

which i want to sort alphabetically.

For this i created a TreeMap:

Map<List<String>, List<Drawable>> myMapToSort = new TreeMap<List<String>, List<Drawable>>();
myMapToSort.put(names, drawables);

First two Question

Is the map now sorted in lexicographical order? Or do i Need to do something additional?

After i have sorted them, if they are yet, i want to split them back again to List<String> and List<Drawable>. And i tried like this:

List<String> sortedNames = new ArrayList<String>(myMapToSort.keySet());

Of course it doesn't work because myMapToSort.keySet() Returns a Set and not List. And List doesn't have an Constructor for a Set.

So how can i accomplish that and what i'm misunderstanding?

Any help is appreciated. Thanks in advance!


Solution

  • I figured it out by my own.

    The key was to create a TreeMap with not two list but two single Objects:

    Map<String, Drawable> myTreeMap = new TreeMap<String, Drawable>;
    

    Then add the Items from the Arraylists one by one to the Map:

    for(int i = 0; i<names.size(); i++) {
            myTreeMap.put(names.get(i), drawables.get(i));
    }
    

    Now the Map is automatically sorted Lexicographical in relation with the Drawables. That means Names and Drawables are sorted in lexicographical order.

    If you want to retrieve the keys and the values and put them back in seperate ArrayLists simply type:

    List <String> mySortedNames = new ArrayList<String>(myTreeMap.keySet());
    List <Drawables> mySortedDrawables = new ArrayList<Drawables>(myTreeMap.values());
    

    That's it. ;)