我想创建根据值排序的唯一键值对的前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