我有两个ArrayLists
:
List<String> names = new ArrayList<String>(10);
List<Drawable> drawables = new ArrayList<Drawable>(10);
我想按字母顺序排序。
为此我创建了一个 TreeMap
:
Map<List<String>, List<Drawable>> myMapToSort = new TreeMap<List<String>, List<Drawable>>();
myMapToSort.put(names, drawables);
前两个问题
map 现在是在lexicographical
中排序的吗?命令?或者我需要做一些额外的事情吗?
在我对它们进行排序之后,如果它们还存在,我想再次将它们拆分回 List<String>
和 List<Drawable>
.我试过这样:
List<String> sortedNames = new ArrayList<String>(myMapToSort.keySet());
当然不行,因为myMapToSort.keySet()
返回 Set
而不是 List
.
和 List
没有 Constructor
对于 Set
.
那么我怎样才能做到这一点以及我误解了什么?
感谢任何帮助。提前致谢!
最佳答案
我自己想出来的。
关键是创建一个 TreeMap
,它不是两个列表,而是两个单独的对象:
Map<String, Drawable> myTreeMap = new TreeMap<String, Drawable>;
然后将Arraylists
中的Items
一个一个添加到Map中:
for(int i = 0; i<names.size(); i++) {
myTreeMap.put(names.get(i), drawables.get(i));
}
现在 Map 会根据 Drawables 自动排序 Lexicographical
。
这意味着 Names 和 Drawables 按字典顺序排序
。
如果您想检索键
和值
并将它们放回单独的ArrayLists
中,只需键入:
List <String> mySortedNames = new ArrayList<String>(myTreeMap.keySet());
List <Drawables> mySortedDrawables = new ArrayList<Drawables>(myTreeMap.values());
就是这样。 ;)
关于android - 将 TreeMap<List<>,List<>> 拆分为两个 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27651019/