我想创建根据值排序的前 5 个唯一键值对列表。
我尝试创建一个 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);
}
输出为:
[type=Monarch - confidence=79.447838, type=Monarch - confidence=58.911613, type=Monarch - confidence=56.614368, type=Founding Figure - confidence=48.796387, type=Politician - confidence=38.921349, type=Queen consort - confidence=36.142864]
最佳答案
我认为你的意思是你想使用TreeMap(Map而不是Set)来使用Comparable键来对它们进行排序。 LinkedHashSet 是一个元素集合,它保持它们添加的顺序。
听起来你想要的是
if (rich_types.size() <= 5) {
cellType ct = new cellType(notable.getString("name"), (Double) array.getJSONObject(i).get("score"));
if(!rich_type.contains(ct))
rich_types.add(ct);
}
关于java - LinkedHashSet 中的唯一 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9466172/