質問

値に応じてソートされた固有キー値ペアの上位5リストを作成したい。

ハッシュマップを作成しようとしましたが、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 - confixcy= 79.447838、Type= Monarch - Convency= 58.911613、Type= Monarch - Convency= 56.614368、Type= Finding Figure - Covence= 48.796387、Type= Politiatian - Conficum= 38.921349、Type= Queen Consort - 信頼= 36.142864]

役に立ちましたか?

解決

私はあなたが彼らを並べ替えるために同等の鍵を使うためにTreeMap(Map Not Set)を使うことを意味すると思います。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);
}
.

他のヒント

HASHCODE()を実装する必要があります。
等価()とhashcode()を実装すると考える人が少なくともこの章を読む必要があります。効果的なJavaまたはより良い本全体の

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top