Answer the question
In order to leave comments, you need to log in
Java. How can I make a search in a collection display all matching elements?
In the phone book, the getRecord method does a search by last name, but it returns only one contact, and it is necessary that if there are several contacts with the same last name, show them all.
import java.util.HashMap;
public class PhoneBook {
private HashMap<String, String> phoneBook = new HashMap<>();
public PhoneBook() {}
public void addRecord(String surName, String phoneNumber) {
phoneBook.put(surName, phoneNumber);
}
public String getRecord(String surName) {
String phoneNumber = phoneBook.get(surName);
if (phoneNumber == null) return "Запись не найдена";
return phoneNumber;
}
}
Answer the question
In order to leave comments, you need to log in
Map on one key stores only one value. Either use a different collection or store a list of contacts in the Map.
Variant with storing the list in Map:
private HashMap<String, List<String>> phoneBook = new HashMap<>();
phoneBook.computeIfAbsent(surName, l -> new ArrayList<>()).add(phoneNumber);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question