如何实现HashMap存储HashSet<Person>的索引与打印功能?
Solution to Populate Index and Print Persons
First, let's fix the indexDB method to correctly populate your index HashMap. There are a couple of key adjustments needed in your initial code:
- The static
indexDBmethod can't access the non-staticindexHashMap by default—let's makeindexstatic to match the method's scope (or adjust the method to non-static if that fits your design better). - You need to retrieve the
namefrom eachPersonobject inlistB(we'll assume yourPersonclass has agetName()getter method). - When a
Person's name matchesbase, we need to ensure thebasekey exists inindex(creating a newHashSetif it doesn't) before adding thePersonto the set.
Here's the corrected code for the index setup and indexDB method:
// Make index static to be accessible from the static indexDB method private static HashMap<String, HashSet<Person>> index = new HashMap<>(); // Assume listB is a static array of Person elements as you mentioned private static Person[] listB; public static void indexDB(String base) { for (Person person : listB) { String personName = person.getName(); if (personName.equals(base)) { // Use computeIfAbsent to handle missing keys cleanly (Java 8+) index.computeIfAbsent(base, key -> new HashSet<>()).add(person); } } }
Quick Explanation:
computeIfAbsentchecks if thebasekey exists in the HashMap. If not, it creates a newHashSetand links it to the key. It then returns the existing or new set, so we can directly add the matchingPersonto it.- For older Java versions without
computeIfAbsent, you can handle this manually:HashSet<Person> personSet = index.get(base); if (personSet == null) { personSet = new HashSet<>(); index.put(base, personSet); } personSet.add(person);
Next, let's implement the printPersons method. This will retrieve the HashSet for the given key and print all associated Person objects, with safeguards for missing keys:
public void printPersons(String sth) { HashSet<Person> persons = index.get(sth); if (persons == null || persons.isEmpty()) { System.out.println("No persons found for key: " + sth); return; } System.out.println("Persons matching key '" + sth + "':"); for (Person person : persons) { // Ensure your Person class has an overridden toString() method for meaningful output System.out.println(person); } }
Important Note:
Make sure your Person class has a properly overridden toString() method to display useful information when printed. For example:
public class Person { private String name; // Add other fields, constructors, and getName() method here @Override public String toString() { return "Person{name='" + name + "'}"; // Include other fields like age if needed } }
内容的提问来源于stack exchange,提问作者mykael
相关产品推荐
相关产品推荐

