我想創建根據值排序的唯一鍵值對的前5列表。LinkedHashSet中的唯一Java對象
我試圖創建一個HashMap但因爲我是從JSON讀取原始列表進行排序的Hashmap覆蓋的最後一個值,使他們關鍵還得最小的值,而不是最大的。
的解決方案是使用LinkedHashSet,以確保其唯一性,並保持秩序。但是因爲我存儲了一個鍵值對,所以我決定創建一個新類並將它們保存爲對象。
我知道,我必須實現媲美,但顯然沒有比較發生和LinkedHashSet是不是唯一的。
我的代碼是:
public class cellType implements Comparable<Object> {
private String type;
private double confidence;
@Override
public String toString() {
return "type=" + type + " - confidence=" + confidence ;
}
public cellType(String type, double confidence) {
super();
this.type = type;
this.confidence = confidence;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getConfidence() {
return confidence;
}
public void setConfidence(double confidence) {
this.confidence = confidence;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof cellType)) {
return false;
}
cellType ct = (cellType) obj;
return type.equals(ct.getType());
}
@Override
public int compareTo(Object o) {
cellType ct = (cellType) o;
return type.compareTo(ct.getType());
}
}
public static void main(String args[]) throws IOException, JSONException {
String freebaseAddress = "https://www.googleapis.com/freebase/v1/search?query=";
System.setProperty("https.proxyHost", "proxy");
System.setProperty("https.proxyPort", "8080");
JSONObject json = readJsonFromUrl(freebaseAddress + "apple");
LinkedHashSet<cellType> rich_types = new LinkedHashSet<cellType>();
JSONArray array = json.getJSONArray("result");
for (int i = 0; i < array.length(); i++) {
if (array.getJSONObject(i).has("notable")) {
JSONObject notable = new JSONObject(array.getJSONObject(i)
.getString("notable"));
if (rich_types.size() <= 5)
rich_types.add(new cellType(notable.getString("name"), (Double) array.getJSONObject(i).get("score")));
}
}
System.out.println(rich_types);
}
的輸出是:
[類型=君主 - 信心= 79.447838,類型=君主 - 信心= 58.911613, type = Monarch - confidence = 56.614368,type = Founding Figure - confidence = 48.796387,type = Politician - confidence = 38.921349,type = Queen consort - confidence = 36.1428 64]
我已經通過使用HashMap和檢查項不存在將解決這個問題,但我不喜歡這樣的解決方案,我想這應該可以解決更優雅 – AhmadAssaf 2012-02-27 14:32:42