K
K
Koshkasobaka2020-11-12 12:35:40
Java
Koshkasobaka, 2020-11-12 12:35:40

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

1 answer(s)
C
Cheypnow, 2020-11-12
@Koshkasobaka

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<>();

Accordingly, you need to add to the list stored by last name:
phoneBook.computeIfAbsent(surName, l -> new ArrayList<>()).add(phoneNumber);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question