如何通过String查找键为ArrayList<String>的Hashtable对应值?
Got it, let's work through this problem. The key thing to note here is that your Hashtable uses ArrayList<String> as its keys—so you can't just pass str1 or str2 directly to the get() method (that would look for an ArrayList key exactly equal to your string, which doesn't exist). Instead, we need to loop through the hashtable's entries and check if any of the key ArrayLists include your target string.
Step 1: Build a Helper Method
First, let's make a reusable method that takes your target string and the hashtable, then returns the matching direction:
private static String getDirectionByKeyword(String keyword, Hashtable<ArrayList<String>, String> directionTable) { // Loop through each entry in the hashtable for (var entry : directionTable.entrySet()) { ArrayList<String> keyList = entry.getKey(); // Check if the key's ArrayList contains the target keyword if (keyList.contains(keyword)) { return entry.getValue(); } } // Return null or a default value if no match is found return null; }
Step 2: Update the Main Method
Now use this helper method in your main to fetch and print the values for str1 and str2:
public static void main(String[] args) { // Print str1's corresponding direction System.out.println(getDirectionByKeyword(str1, compassDirection)); // Outputs "North" // Print str2's corresponding direction System.out.println(getDirectionByKeyword(str2, compassDirection)); // Outputs "North" }
Full Modified Code
Putting everything together, your complete class will look like this:
package com; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.Map; public class TestMain { private static final String str1 = "n"; private static final String str2 = "north"; private static final Hashtable<ArrayList<String>, String> compassDirection = new Hashtable<>() {{ put(new ArrayList<>(Arrays.asList("n", "north")), "North"); put(new ArrayList<>(Arrays.asList("s", "south")), "South"); put(new ArrayList<>(Arrays.asList("e", "east")), "East"); put(new ArrayList<>(Arrays.asList("w", "west")), "West"); }}; private static String getDirectionByKeyword(String keyword, Hashtable<ArrayList<String>, String> directionTable) { for (Map.Entry<ArrayList<String>, String> entry : directionTable.entrySet()) { if (entry.getKey().contains(keyword)) { return entry.getValue(); } } return null; } public static void main(String[] args) { // Print str1 as "North" from hashtable call System.out.println(getDirectionByKeyword(str1, compassDirection)); // Print str2 as "North" from hashtable call System.out.println(getDirectionByKeyword(str2, compassDirection)); } }
Quick Notes
- If you need case-insensitive matching (e.g., matching "NORTH" or "N"), swap
keyList.contains(keyword)withkeyList.stream().anyMatch(s -> s.equalsIgnoreCase(keyword)). Hashtableis thread-safe, but if you don't need thread safety,HashMapis a more modern and efficient alternative.
内容的提问来源于stack exchange,提问作者Fiddle Freak

