有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何打印特定Hashmap键的所有值

当前问题:我构建了一个HashMap来保存和检索一些键和值。但我不确定如何通过特定的名称(字符串)检索所有值。目前,它正在打印Hashmap中的所有值,这不是我想要实现的目标

在下面的示例中,我使用以下字段

字段

String name
// Object Example

HashMap

Map<String,Example> mapOfExampleObjects = new HashMap<String,Example>();

for循环通过某个键名从hashmap中检索值

for(Map.Entry<String,Example> entry: mapOfExampleObjects.entrySet()){
                    if(mapOfExampleObjects.containsKey(name))
                    {
                    System.out.println(entry.getKey() + " " + entry.getValue());
                    }
                }

电流输出

John + (Exampleobject)
Ian + (Exampleobject)
Ian + (Exampleobject)
Jalisha + (Exampleobject)

我想要实现的输出

Ian + (Exampleobject)
Ian + (Exampleobject)

共 (2) 个答案

  1. # 1 楼答案

    拉尔斯,你的问题是这句话:

                if(mapOfExampleObjects.containsKey(name))
    

    每次通过循环时,mapOfExampleObjects始终包含键“Ian”。你想要的更像:

    if( name.equals(entry.getKey()) )
    
  2. # 2 楼答案

    您可以提取映射的keySet并对其进行操作以选择所需的条目:

    class Example {
    
        final String name;
    
        Example(String name) {
            this.name = name;
        }
    
        public String toString() {
            return name;
        }
    }
    
    public void test() {
        // Sample data.
        Map<String, Example> mapOfExampleObjects = new HashMap<String, Example>();
        mapOfExampleObjects.put("John", new Example("John Smith"));
        mapOfExampleObjects.put("Ian", new Example("Ian Bloggs"));
        mapOfExampleObjects.put("Ian", new Example("Ian Smith"));
        mapOfExampleObjects.put("Jalisha", new Example("Jalisha Q"));
        // Using a Set you can extract many.
        Set<String> want = new HashSet<String>(Arrays.asList("Ian"));
        // Do the extract - Just keep the ones I want.
        Set<String> found = mapOfExampleObjects.keySet();
        found.retainAll(want);
        // Print them.
        for (String s : found) {
            System.out.println(mapOfExampleObjects.get(s));
        }
    }
    

    请注意,这仍然只会打印一个Ian,因为Map对每个键只保留一个值。您需要使用不同的结构(可能是Map<String,List<Example>>)来针对每个键保留多个值