我正在访问这个 API,它可以为我提供全局天气信息:
https://callforcode.weather.com/doc/v3-global-weather-notification-headlines/
但是,它需要 lat/lng 作为输入参数,我需要整个世界的数据。
我想我可以遍历每个纬度经度,每 2 个纬度和 2 个经度,给我一个世界上的点,每 120 英里宽,大约 100 度北/南,这应该给我所有的数据16,200 次 API 调用 ((360/2) * (180/2))。
如何在 Java 中有效地做到这一点?
我想到了这样的东西;但有更好的方法吗?
for(int i = 0; i < 360; i+2){
var la = i;
for(int x = 0 x < 180; x+2) {
var ln = x;
//call api with lat = i, lng = x;
}
}
最佳答案
这在某种程度上是一种范式转变,但是我不会使用嵌套的 for 循环来解决这个问题。在许多情况下,当您考虑迭代整个结果集时,通常可以大幅削减覆盖范围,而不会损失太多或任何有效性。 缓存、修剪、优先级...这些是您需要的东西:而不是 for 循环。
- 完全切割部分 - 也许您可以忽略海洋,也许您可以忽略南极洲和北极(因为那里的人们无论如何都有更好的方法来检查天气)
- 根据人口密度更改搜索频率。也许加拿大北部不需要像洛杉矶或芝加哥那样彻底检查。
- 依赖低使用率区域的缓存 - 您大概可以跟踪哪些区域正在实际使用,然后可以更频繁地刷新这些部分。
因此,您最终得到的是某种加权缓存系统,该系统考虑人口密度、使用模式和其他优先级来确定要检查的纬度/经度坐标以及频率。 高级代码可能如下所示:
void executeUpdateSweep(List<CoordinateCacheItem> cacheItems)
{
for(CoordinateCacheItem item : cacheItems)
{
if(shouldRefreshCache(item))
{
//call api with lat = item.y , lng = item.x
}
}
}
boolean shouldRefreshCache(item)
{
long ageWeight = calculateAgeWeight(item);//how long since last update?
long basePopulationWeight = item.getBasePopulationWeight();//how many people (users and non-users) live here?
long usageWeight = calculateUsageWeight(item);//how much is this item requested?
return ageWeight + basePopulationWeight + usageWeight > someArbitraryThreshold;
}
关于java - 如何在 Java 中迭代每个纬度/经度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52260948/