【问题标题】:Sort ArrayList by double values按双值对 ArrayList 进行排序
【发布时间】:2015-07-08 20:51:06
【问题描述】:

我有一个具有双值的 ArrayList:

double distance = HaversineAlgorithm.HaversineInKM(lat, lon,
                    stop.getStopLat(), stop.getStopLon());
distanceList.add(distance);

我可以用这个得到列表中的最小值:

int minIndex = distanceList.indexOf(Collections.min(distanceList));
currentList.get(minIndex); //it is the smallest value element

但我也必须知道第二个最小值和第三个最小值元素。但我不知道怎么做。

我试图用这个对列表进行排序:

Collections.sort(distanceList);

但它不起作用。我的意思是 List 的最后一个索引不是最小值或最大值。

这里有人可以解释我如何解决这个问题吗? :)

【问题讨论】:

  • 排序后,min 元素位于索引 0(假设排序是自然顺序),因此您希望元素位于索引 1。也许您应该澄清“但它不起作用。”
  • 这将按升序排列,所以,sort() 之后,distanceList.get(0) 是最小的,distanceList.get(1) 是第二小的,依此类推...
  • currentList.get(minIndex + 1); 为第二大,currentList.get(minIndex + 2); 为第三大

标签: java sorting arraylist


【解决方案1】:

这段代码看起来不错:

int minIndex = distanceList.indexOf(Collections.min(distanceList));
currentList.get(minIndex); //it is the smallest value element

所以由于一切都是有序的,你可以通过直接调用索引来获得最小的、第二小的和第三小的值。

    currentList.get(0);
    currentList.get(1);
    currentList.get(2);

【讨论】:

  • 谢谢,对不起,我的问题还不够清楚.. :( 我有两个 ArrayList: currentList 其中包括实体对象.. 和 HaversineAlgorithm 我正在检查两个 gps 坐标之间的距离..我把值放到另一个ArrayList这是distanceList ..我知道哪个是我的distanceList中最小的double值,但我不知道如何指向另一个包含我的实体的ArrayList .. :)也许我应该使用哈希映射..
  • HashMap 听起来比使用两个数组更好。试试看它是否有效,如果它没有发布新问题,我们将为您提供帮助
猜你喜欢
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-22
相关资源
最近更新 更多