Can I get all the values of HashMap elements, having the same keys? (Java)

為{幸葍}努か 提交于 2019-12-27 04:48:20

问题


I have a task given me on the Java programming course. According to this task I have to create a method that returns a number of the HashMap elements with identical keys. But the problem is that the iterator goes through elements with different keys only, so anyway, the method returns 1. What`s the way out?

package com.javarush.test.level08.lesson08.task03;

import java.util.*;

/* Одинаковые имя и фамилия
Создать словарь (Map<String, String>) занести в него десять записей по   принципу «Фамилия» - «Имя».
Проверить сколько людей имеют совпадающие с заданным имя или фамилию.
*/

public class Solution
{
    public static void main(String[] args)
    {
        HashMap<String, String> friends = createMap();
        getCountTheSameLastName(friends, "гладких");
        getCountTheSameFirstName(friends, "Виталий");
    }

    public static HashMap<String, String> createMap()
    {
        HashMap<String, String> name = new HashMap<String, String>();

        name.put("гладких", "Иван");
        name.put("пересыпкин", "Артем");
        name.put("пересыпкин", "Владислав");
        name.put("халитов", "Виталий");
        name.put("чернышев", "Виталий");
        name.put("ивинских", "Виталий");
        name.put("ивинских", "Альфред");
        name.put("осипова", "Мария");
        name.put("ивинских", "Павел");
        name.put("гейтс", "Билл");

        return name;
    }

    public static int getCountTheSameFirstName(HashMap<String, String>         map, String name)
    {
        int MatchesFirstnameCount = 0;

        for (HashMap.Entry<String, String> pair : map.entrySet()) {
            String s = pair.getValue();
            if (s.equals(name) ) {
                MatchesFirstnameCount++;
            }
        }

        return MatchesFirstnameCount;
    }

    public static int getCountTheSameLastName(HashMap<String, String>     map, String lastName)
    {
        int MatchesSecondnameCount = 0;

        for (HashMap.Entry<String, String> pair : map.entrySet()) {
            if (pair.getKey().equals(lastName))
                MatchesSecondnameCount++;
        }
        return MatchesSecondnameCount;
    }
}

回答1:


This sounds like a trick question. Each key in a HashMap can only have one value associated with it. Each key in a HashMap must be unique.

When adding a duplicate key the old value is replaced (see HashMap.put)




回答2:


This sounds like a tricky question. The key in HashMap must be unique. If you want to store multiple elements on the same key, you can save a collection like:

Map<Integer, List<Object>> map = new HashMap<>();

Then, the following method would return a List.

map.get(0) 


来源:https://stackoverflow.com/questions/40290968/can-i-get-all-the-values-of-hashmap-elements-having-the-same-keys-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!