Can I get all the values of HashMap elements, havi

2019-09-22 00:33发布

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

标签: java hashmap key
2条回答
smile是对你的礼貌
2楼-- · 2019-09-22 01:20

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) 
查看更多
神经病院院长
3楼-- · 2019-09-22 01:35

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)

查看更多
登录 后发表回答