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;
}
}
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:
Then, the following method would return a List.
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)