简体   繁体   English

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

[英]put and get for nested hashmap in java

I am really new to Java and I am trying to implement something using Hashmap. 我对Java真的很陌生,我正在尝试使用Hashmap实现某些东西。

The following code is what I declared first: 下面的代码是我首先声明的:

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

And, 和,

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");
        }
}

this is what I am writing at the moment. 这就是我目前正在写的。 Assuming that there are items called "person", "data" and "grade". 假设存在称为“人”,“数据”和“等级”的项目。 Can someone please tell me how to put them in the nested hashmap? 有人可以告诉我如何将它们放入嵌套的哈希图中吗? I finished writing the getter and setter for each of the items in another class called, MySubmissions. 我完成了另一个类MySubmissions中每个项目的getter和setter的编写。

The Submission is an interface written in another class that contain the following methods: Submission是用另一个类编写的接口,其中包含以下方法:

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

What I want to achieve is that, for example, 我想要实现的是,例如,

?.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);

Thanks! 谢谢!

(what I exactly want to achieve is, I want to add data into the hashmap. And then using another method called, getBestGrade, I want to get the best graded person among the list but I just want to know how to store into the hashmap first using put and get...) (我真正想要实现的是,我想将数据添加到哈希图中。然后使用另一种名为getBestGrade的方法,我想获得列表中评分最高的人员,但是我只想知道如何存储到哈希图中首先使用put and get ...)

Create an entity 创建一个实体

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;
    }
}

Create a HashMap 创建一个HashMap

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

Do add 做添加

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

I think he wants to know how to store more than one Submission for each Person. 我认为他想知道如何为每个人存储多个提交。 You can do something like this: 您可以执行以下操作:

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;
    }
}

I'm just going to describe how to use a map of maps -- it's up to you to decide whether this is what you actually want to use. 我将仅描述如何使用地图地图-由您决定这是否是您真正想要使用的地图。 I'm going to use classes called A , B , C etc. -- you can substitute your own, including String or Submission if you like. 我将使用称为ABC等的类-如果愿意,您可以替换自己的类,包括StringSubmission

Make sure you have a firm understanding of a single-level Map before you tackle this -- how equals() and hashCode() are necessary for HashMap etc. 在解决此问题之前,请确保您对单级Map有深刻的理解HashMap等如何需要equals()hashCode()

You can define a map of maps much as you have done: 您可以像完成许多操作一样定义地图:

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

In general, give variables a type of Map rather than HashMap or TreeMap -- you normally don't need any of the more specific methods of the implementation classes. 通常,为变量提供一种Map类型,而不是HashMapTreeMap -您通常不需要实现类的任何更具体的方法。 You can always change up if you do. 如果这样做,您总是可以更改的。 The ? extends Map<> ? extends Map<> ? extends Map<> part allows your map-of-maps to contains arbitrary implementations of Map . ? extends Map<>部分允许您的地图包含Map任意实现。

You can instantiate this like this: 您可以这样实例化:

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>>();

Now you have an empty map-of-maps. 现在您有一个空的地图。 You can add a map to it: 您可以向其中添加地图:

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

Now you have a map-of-maps containing one empty map. 现在,您有了一个包含一个空地图的地图。 Or you could add a map containing something: 或者,您可以添加包含以下内容的地图:

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

Plausibly, you want to add items to a Map<B,C> when you don't know whether it exists. 可能是,您想在不知道Map<B,C>是否存在的情况下添加项目。 There's no short-cut here - you have to do: 这里没有捷径-您必须执行以下操作:

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);
}

Note that this has problems if multiple threads are doing it at the same time. 请注意,如果多个线程同时执行此操作,则会出现问题。

Likewise if you're just reading, you have to handle missing elements at both levels: 同样,如果您只是阅读,则必须在两个级别上处理缺失的元素:

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

(Or more compactly) (或更紧凑)

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