【问题标题】:Sort a List based on another List根据另一个 List 对 List 进行排序
【发布时间】:2015-01-02 22:19:10
【问题描述】:

我目前有一个字符串 id 的有序列表 (List<String>) 和一个自定义类的无序列表 (List<CustomClass>)。我想根据 IDS 的有序列表对自定义类对象的列表进行排序。

我的印象是最好的方法是使用 TreeMap。所以我实现了这个:

Map<String, CustomClass> mapB = new HashMap<String, CustomClass>();
    for (String id : mIds) {
        for (CustomClass customClass : mCustomClass) {                
            mapB.put(thingId, mCustomClass);
        }
    }

Map<String, CustomClass> treeMap = new TreeMap<String, CustomClass>();
treeMap.putAll(mapB);

虽然它可以很好地存储所有 id,但是当我打印出 TreeMap 时,它似乎只需要 mapB 的最后一个值并存储它。 IE。日志示例:

地图:1:巴黎,地图:2:巴黎,地图:3:巴黎

但我补充的是:

mapB.put("1", London);
mapB.put("2", Berlin);
mapB.put("3", Paris);

所以是的,我对正在发生的事情有点困惑,有人可以提供一些指导吗?谢谢!

【问题讨论】:

  • List 中的字符串是否存在于 CustomClass 中?
  • 这个id是从这个类的模型中访问的,但它没有被存储为局部变量或任何东西。
  • 请提供 List 和 List 之间的关系以及 CustomeClass 的实现。如果 CustomClass 中的任何字段对应于 List 中存在的任何项目

标签: java android list map treemap


【解决方案1】:

这是因为您使用了两个 fors。因此,这会在地图中添加值: 1 - 伦敦 1 - 柏林 1 - 巴黎 2 - 伦敦 2 - 柏林 2 - 巴黎 3 - 伦敦 3 - 柏林 3 - 巴黎

TreeMap 只记住您为每个索引输入的最后一个值,因此所有索引都是 Paris。

如果您知道 mIds 和 mCustomClass [相同长度] 中有相应的元素,只需使用一个 for 并简单地使用 mapB.put(mIds[i], mCustomClass[i])。

对于更通用的方法,如果您在两个数组(或集合)中有相应的项目,您应该考虑创建一个更好的对象,具有 2 个字段(id 和 class)并简单地为该对象编写您自己的 Comparator,即只考虑 ID。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-11
    • 2010-10-17
    • 2016-06-26
    • 2019-07-02
    • 2020-11-18
    • 2021-03-26
    • 1970-01-01
    • 2017-01-12
    相关资源
    最近更新 更多