簡體   English   中英

在Java中放置和獲取嵌套的hashmap

[英]put and get for nested hashmap in java

我對Java真的很陌生,我正在嘗試使用Hashmap實現某些東西。

下面的代碼是我首先聲明的:

private HashMap<String, TreeMap<Object, Object>> submissions = new HashMap<String, TreeMap<Object, Object>>();;

和,

public Submission add(String unikey, Date timestamp, Integer grade) {

        // check the argument
        if(unikey == null || timestamp == null || grade == null) {
            throw new IllegalArgumentException("Null argument detected\n");
        }
}

這就是我目前正在寫的。 假設存在稱為“人”,“數據”和“等級”的項目。 有人可以告訴我如何將它們放入嵌套的哈希圖中嗎? 我完成了另一個類MySubmissions中每個項目的getter和setter的編寫。

Submission是用另一個類編寫的接口,其中包含以下方法:

public String getPerson();
public Date getTime();
public Integer getGrade();

我想要實現的是,例如,

?.add("aaaa1234", df.parse("2016/09/03 09:00:00"), 10);
?.add("aaaa1234", df.parse("2016/09/03 16:00:00"), 20);
?.add("cccc1234", df.parse("2016/09/03 16:00:00"), 30);
?.add("aaaa1234", df.parse("2016/09/03 18:00:00"), 40);

謝謝!

(我真正想要實現的是,我想將數據添加到哈希圖中。然后使用另一種名為getBestGrade的方法,我想獲得列表中評分最高的人員,但是我只想知道如何存儲到哈希圖中首先使用put and get ...)

創建一個實體

public class Submission {

    private Date timestamp;

    private Integer grade;


    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

    public Integer getGrade() {
        return grade;
    }

    public void setGrade(Integer grade) {
        this.grade = grade;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Submission that = (Submission) o;

        if (timestamp != null ? !timestamp.equals(that.timestamp) : that.timestamp != null) return false;
        return grade != null ? grade.equals(that.grade) : that.grade == null;
    }

    @Override
    public int hashCode() {
        int result = timestamp != null ? timestamp.hashCode() : 0;
        result = 31 * result + (grade != null ? grade.hashCode() : 0);
        return result;
    }
}

創建一個HashMap

private HashMap<String, Submission> map = new HasMap<>();

做添加

map.add("key", new Submission());

我認為他想知道如何為每個人存儲多個提交。 您可以執行以下操作:

import java.util.Date;
import java.util.HashMap;
import java.util.TreeMap;

public final class BestGrade
{
    private static final HashMap<String, TreeMap<Date, Integer>> SUBMISSIONS = new HashMap<String, TreeMap<Date, Integer>>();

    private BestGrade()
    {}

    public static void main(final String[] args)
    {
        // How to add
        add("Person1", new Date(), Integer.valueOf(1));
        add("Person1", new Date(), Integer.valueOf(10));
        add("Person1", new Date(), Integer.valueOf(20));
        add("Person2", new Date(), Integer.valueOf(1));
        add("Person3", new Date(), Integer.valueOf(30));
        add("Person3", new Date(), Integer.valueOf(40));

        // How to get best grade
        final Integer bestGradePerson1 = getBestGrade("Person1");
        final Integer bestGradePerson3 = getBestGrade("Person2");
        final Integer bestGradePerson2 = getBestGrade("Person3");

        System.out.println("Bestgrade Person1: " + bestGradePerson1);
        System.out.println("Bestgrade Person2: " + bestGradePerson2);
        System.out.println("Bestgrade Person3: " + bestGradePerson3);
    }

    public static void add(final String key, final Date timestamp, final Integer grade)
    {
        // TODO the same for timestamp and grade
        if (key == null || key.trim().isEmpty()) {
            throw new IllegalArgumentException("key must not be null");
        }

        // Get
        TreeMap<Date, Integer> submission = SUBMISSIONS.get(key);
        // Create your treemap if not already exists, before adding new value to avoid NullPointerException
        if (submission == null) {
            submission = new TreeMap<Date, Integer>();
            SUBMISSIONS.put(key, submission);
        }
        submission.put(timestamp, grade);
    }

    public static Integer getBestGrade(final String key)
    {
        Integer bestGrade = null;

        final TreeMap<Date, Integer> submission = SUBMISSIONS.get(key);
        if (submission == null) {
            // When no submission available, return null or any other value you wish to show there is no best grade
            return bestGrade;
        }

        for (final Integer grade : submission.values()) {
            if (bestGrade == null) {
                bestGrade = grade;
            }
            // Set new grade when values is higher than before
            else if (bestGrade.intValue() < grade.intValue()) {
                bestGrade = grade;
            }
        }
        return bestGrade;
    }
}

我將僅描述如何使用地圖地圖-由您決定這是否是您真正想要使用的地圖。 我將使用稱為ABC等的類-如果願意,您可以替換自己的類,包括StringSubmission

在解決此問題之前,請確保您對單級Map有深刻的理解HashMap等如何需要equals()hashCode()

您可以像完成許多操作一樣定義地圖:

Map<A, ? extends Map<B,C>> mapOfMaps;

通常,為變量提供一種Map類型,而不是HashMapTreeMap -您通常不需要實現類的任何更具體的方法。 如果這樣做,您總是可以更改的。 ? extends Map<> ? extends Map<>部分允許您的地圖包含Map任意實現。

您可以這樣實例化:

Map<A, ? extends Map<B,C>> mapOfMaps = new HashMap<>();
// or with explicit (unnecessary) type declarations:
Map<A, ? extends Map<B,C>> mapOfMaps = new HashMap<A, ? extends Map<B,C>>();

現在您有一個空的地圖。 您可以向其中添加地圖:

Map<B,C> map = new HashMap<>();
mapOfMaps.put(new A(1), map);

現在,您有了一個包含一個空地圖的地圖。 或者,您可以添加包含以下內容的地圖:

Map<B,C> map = new HashMap<>();
map.put(b, c);
mapOfMaps.put(a, map);

可能是,您想在不知道Map<B,C>是否存在的情況下添加項目。 這里沒有捷徑-您必須執行以下操作:

void addToMapOfMaps(A a, B b, C c) {
   Map<B,C> map = mapOfMaps.get(a);
   if(map == null) {
      map = new HashMap<>();
      mapOfMaps.put(a,map);
   }
   map.put(b,c);
}

請注意,如果多個線程同時執行此操作,則會出現問題。

同樣,如果您只是閱讀,則必須在兩個級別上處理缺失的元素:

C get(A a, B b) {
    Map<B,C> map = mapOfMaps.get(a);
    if(map == null) {
         return null;
    }
    return map.get(b);
}

(或更緊湊)

C get(A a, B b) {
    Map<B,C> map = mapOfMaps.get(a);
    return map == null ? null : map.get(b);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM