2016-04-30 68 views
0

所以我正在开发一个使用Fabric API的丢失和找到的应用程序。它可以根据用户的当前位置对收集的推文进行排序。我发现在线方式使用比较器进行排序。然而,这似乎并不奏效,而前分类和后分类结果完全相同。Twitter的织物API:根据位置排序tweets(最近的第一个)

public class SortLocations implements Comparator<Tweet> { 
    Double currLat; 
    Double currLng; 

    public SortLocations(Double currLat1, Double currLng1) { 
     currLat = currLat1; 
     currLng = currLng1; 
    } 

    @Override 
    public int compare(final Tweet tweet1, final Tweet tweet2) { 
     double lat1 = 0, lon1 = 0, lat2 = 0, lon2 = 0, distanceToPlace1 = 0, distanceToPlace2 = 0; 
     try { 
      lat1 = tweet1.coordinates.getLatitude(); 
      lon1 = tweet1.coordinates.getLongitude(); 

      lat2 = tweet2.coordinates.getLatitude(); 
      lon2 = tweet2.coordinates.getLongitude(); 

      distanceToPlace1 = distance(currLat, currLng, lat1, lon1); 
      distanceToPlace2 = distance(currLat, currLng, lat2, lon2); 
     } catch (Exception E) { 
      Log.d("No coordinates", ""); 
     } 
     return (int) (distanceToPlace1 - distanceToPlace2); 
    } 

    public double distance(double fromLat, double fromLon, double toLat, double toLon) { 
     double radius = 6378137; // approximate Earth radius, *in meters* 
     double deltaLat = toLat - fromLat; 
     double deltaLon = toLon - fromLon; 
     double angle = 2 * Math.asin(Math.sqrt(
       Math.pow(Math.sin(deltaLat/2), 2) + 
         Math.cos(fromLat) * Math.cos(toLat) * 
           Math.pow(Math.sin(deltaLon/2), 2))); 
     return radius * angle; 
    } 
} 

这是类是如何在我的活动

Collections.sort(tweetsSortedByLocation, new SortLocations(currLat, currLng)); 

哪里tweetsSortedByLocation的类型是List使用。任何帮助真的很感激:)

回答

1

我可能会建议一个稍微不同的方法,这将使您的生活更容易一点,而不会损失任何计算时间。

您当前的解决方案可能是n + n log(n)time:n用于向集合添加Tweets,然后用n log(n)进行排序。如果您使用PriorityQueue(在Java中以min-heap实现)而不是常规列表(因为我假设tweetsSortedByLocation是),那么它会在添加到它时进行排序,从而为您提供n个log(n)时间:n元素和日志(n)为每个插入(认为二进制搜索)。

您可以使用一个PriorityQueue像这样(https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html):

PriorityQueue<Tweet> tweetsSortedByLocation = new PriorityQueue<>(10, new SortLocations(currLat, currLong)); 
tweetsSortedByLocation.add(new Tweet()); // Or however you add them now 

你也可以内嵌的比较,但使用SortLocations更好。

现在,为什么排序时没有任何变化,这意味着compare()每次都必须返回0。

return (int) (distanceToPlace1 - distanceToPlace2); 

如果distanceToPlace1和distanceToPlace2没有比差1以上,即整数投带来了它:如果你计算两个距离之间的差值小于1。看在这条线的整铸这将发生为0,在比较必须实施的情况下,意味着平等。 (见https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html)。那么,试试这个,而不是(至少到第一排序距离(即通过距离ASC)):

if (distanceToPlace1 < distanceToPlace2) { 
    return -1; 
} else if (distanceToPlace1 > distanceToPlace2) { 
    return 1; 
} else { 
    return 0; 
} 

我希望解决您的问题

+0

感谢您的答复!扎克非常感谢您的全面解决方案。 –