从具有多个值的 Hashmap 中获取其中一个值

Get one of the values from Hashmap with multiple values

如果我有一个Hashmap如下:

Hashmap<String, Node> nodeMap = new HashMap<String, Node>();

并且 Node 存储多个值,包括:

String name,
int year,
double weight

如何打印出存储在该哈希图中的多个值之一? 我实际上不知道只打印其中一个值(这是我最需要的) 但作为开始,我尝试先使用以下查询打印所有值

Set<String> keySet= nodeMap.keySet();
    for(String x:keySet){
        System.out.println(nodeMap.get(x));
    }

但是,我得到了一个输出,例如 Node@73a28541, Node@6f75e721, Node@69222c14.

我正在尝试获取 Hashmap 中每个键的名称、年份和权重等的真实值,但它仍然无法正常工作。

我实际上需要知道如何只打印其中一个值..

任何帮助将不胜感激。谢谢

编辑: 这就是我存储 Hashmap 和节点值的方式:

Node n = new Node(resultSet.getString(1), resultSet.getInt(2),weight);
               nodeMap.put(resultSet.getString(1),n);

我的预期输出是,如果我有某个键,例如 123,我想获得 123 键的年份值。

在class节点中,覆盖打印节点时将调用的函数toString,您可以选择打印的显示方式。

for(String key : keySet){
   Node n = map.get(key);
   System.out.println(n.getYear());
}
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class TestMap {
    static class Node {
        public String name;
        public int year;
        public double weight;

        public Node(String name, int year, double weight) {
            this.name = name;
            this.year = year;
            this.weight = weight;
        }

        @Override
        public String toString() {
            // here you can create your own representation of the object
            String repr = "Name:" + name + ",year:" + year + ",weight:" + weight;
            return repr;
            }
        }

    public static void main(String args[]) {
        Map<String, Node> map = new HashMap<String, Node>();
        Node node1 = new Node("A",1987,70.2);
        Node node2 = new Node("B", 2014, 66.4);
        String key1 = "123";
        String key2 = "345";
        map.put(key1,node1);
        map.put(key2,node2);

        Set<String> keySet= map.keySet();
        for(String x:keySet){
            System.out.println(map.get(x));
        }

       System.out.println(map.get(key1).name); 
    }
}

上面的代码应该已经说明了一切。

由于调用了nodeMap.get方法,所以应该使用entrySet方法而不是keySet

这里稍微比较一下两种方法的使用:

// Create Map instance and populate it
Map<String, Node> nodeMap = new HashMap<String, Node>();
for (int i = 0; i < 100; i++) {
    String tmp = Integer.toString(i);
    nodeMap.put(tmp, new Node(tmp, 2015, 3.0));
}

// Test 1: keySet + get
long t1 = System.nanoTime();
for (String x : nodeMap.keySet()) {
    nodeMap.get(x);
}
System.out.format("keySet + get: %d ns\n" , System.nanoTime() - t1);

// Test 2: entrySet + getValue
t1 = System.nanoTime();
for (Map.Entry<String, Node> e : nodeMap.entrySet()) {
    e.getValue();
}
System.out.format("entrySet + getValue: %d ns\n" , System.nanoTime() - t1);

输出

keySet + get: 384464 ns
entrySet + getValue: 118813 ns

我运行反复试验过这个。平均而言,entrySet + getValuekeySet + get 两倍