卡在以下内容:我正在解析xml气象数据,其中包含有关3种不同信息的信息

weather stations:

<station>
<station_id>TAPA</station_id>
<latitude>17.117</latitude>
<longitude>-61.783</longitude>
<xml_url>http://weather.gov/xml/current_obs/TAPA.xml</xml_url>
</station>

<station>
<station_id>TKPN</station_id>
<latitude>17.2</latitude>
<longitude>-62.583</longitude>
<xml_url>http://weather.gov/xml/current_obs/TKPN.xml</xml_url>
</station>

<station>
<station_name>Blackburne/Plymouth</station_name>
<latitude>16.75</latitude>
<longitude>-62.167</longitude>
<xml_url>http://weather.gov/xml/current_obs/TRPM.xml</xml_url>
</station>


接下来,我要获取他们与设备的距离并获取以下数据集:

Distance(Double):        Corresponding XML(String)

3495.3          http://weather.gov/xml/current_obs/TAPA.xml
1234.4          http://weather.gov/xml/current_obs/TKPN.xml
5678.7          http://weather.gov/xml/current_obs/TRPM.xml


最好的方法是将它们按升序放入某种排序的集合中,并以最小的距离获得相应的xml文件?我的意思是,距离将是关键,而相应的XML将是它的价值。排序后,我将获得最小的距离(这是第一个键)并访问我的网址以对其执行其他工作。距离可能会发生变化,因为附近可能还有其他站点,因此我需要以某种方式访问​​第一个键值对。你能给我一个提示吗?

最佳答案

好。它是这样工作的:

为了能够用Java中的sort通过property对象,必须实现Comparable接口。然后,您需要重写名为compareTo()的方法,该方法使用当前实例(this)和另一个实例以正确的顺序对其进行排序。因此,为了能够按站点之间的距离进行排序,您需要执行以下操作:

class Data implements Comparable<Data>{
    String url;
    double distance;

    @Override
    public int compareTo(Data other){
        // compareTo should return < 0 if this is supposed to be
        // less than other, > 0 if this is supposed to be greater than
        // other and 0 if they are supposed to be equal
        int result = this.distance <= other.distance ? -1 : 1;
        return result;
    }
}


完成此操作后,您将可以致电:

Collections.sort(dataList);


并且,您将按照distance属性对对象进行排序。

关于java - 解析天气数据并将其分类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35538827/

10-09 00:16
查看更多