【问题标题】:Sorting ArrayList of model that is connected with a hashmap对与 hashmap 连接的模型的 ArrayList 进行排序
【发布时间】:2018-02-14 13:58:21
【问题描述】:

我有一个模型数组列表和一个哈希图。模型类包含 id(int)、name、address 等变量。 hashmap 包含 id(int) 和 distance (double)。我之前尝试过使用 Collection 对模型列表进行排序,但这里的问题是,我必须通过它的距离值对 hashmap 进行排序,然后根据 hashmap 的排序方式调整 arraylist。 hashmap 的 id 和模型类的 id 在这里充当“外键”。有人知道怎么做吗?

这是哈希图:

HashMap<Integer, String> listDistance = new HashMap<Integer, String>();
listDistance.put(1, 3.22);
listDistance.put(2, 2.57);
listDistance.put(3, 6.32);
listDistance.put(4, 8.82);
listDistance.put(5, 1.32);

这是数组列表:

ArrayList<Listing> listings = new ArrayList<Listing>();
listing.add(1, "asd", 123);
listing.add(2, "ghf", 3434);
listing.add(3, "ert", 876);
listing.add(4, "tyi", 1267);
listing.add(5, "ohg", 1345);

这是模型类:

public class Listing {

int id, count;
String name;

public Listing(int id, String name, int count) {
    this.id = id;
    this.count = count;
    this.name = name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getCount() {
    return count;
}

public void setCount(int count) {
    this.count = count;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

我想要的结果应该对列表进行排序,变成这样:

  1. listing.add(5, "ohg", 1345);
  2. listing.add(2, "ghf", 3434);
  3. listing.add(1, "asd", 123);
  4. listing.add(3, "ert", 876);
  5. listing.add(4, "tyi", 1267);

实际上,除了考虑逻辑流程之外,我没有尝试任何方法来实现这一点,因为我完全不知道如何做到这一点。

【问题讨论】:

  • 展示你已经完成的工作。
  • 尝试 TreeMap 代替 HashMap..,B/W 向我们展示您的代码
  • 能否请您发布一些您的模型的代码以及您现在的排序方式。
  • 您真的需要按值排序的Map&lt;Integer, Double&gt;(无法做到),还是只需要按距离排序的List&lt;Model&gt;(很容易做到)?
  • 是的,只要模型列表可以按距离排序就可以了。但我不认为我可以将距离的值合并到模型列表中。因为数据是单独检索的,要根据id放距离值。或者我可以吗?

标签: java android sorting arraylist hashmap


【解决方案1】:

您可以像这样对列表进行排序:

Collections.sort(listing, (a,b) -> Double.compare(listDistance.get(a.getId()),
                                                  listDistance.get(b.getId())));

查看运行代码IDEONE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 2012-09-28
    • 2015-04-22
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多