我试图按键(即映射中每个单词的第一个字母)获取映射内的所有字符串,但不断删除重复项,结果只剩下几个单词。
public class Search {
private static void searchHashForLetterKey() throws FileNotFoundException {
Map<Character, String> charCount = new HashMap<Character, String>();
Scanner scanner = new Scanner(new File("words.txt"));
String word = "and";
while (scanner.hasNext()) {
char firstChar = scanner.next().charAt(0);
charCount.put(firstChar, scanner.next());
}
// Print out each of the values.
for (Map.Entry<Character, String> entry: charCount.entrySet()) {
char character = entry.getKey();
String count = entry.getValue();
System.out.println(character + ": " + count);
}
if (charCount.containsKey(word.charAt(0))){
System.out.println("KEY FOUND");
if(charCount.containsValue(word.trim())){
System.out.println("Word found is: " + word);
} else {
System.out.println("Your word is not found in the example: " + word);
}
} else {
System.out.println("Key Not Found: " + word);
}
}
public static void main(String[] args) {
System.out.println();
try {
searchHashForLetterKey();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
该文件是一个word.txt文件,其中包含与此相同的英语单词词典:http://www-01.sil.org/linguistics/wordlists/english/wordlist/wordsEn.txt
这是一个工作示例,但仍然不符合预期,仍然无法检查单词的 contains() 。
public static void searchforWords() throws FileNotFoundException {
String match = "add";
List<String> words = new ArrayList(Arrays.asList("cat", "ball", "bat", "cup", "add", "ant"));
Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
for(String word: words){
String firstChar = String.valueOf(word.charAt(0));
if (map.get(firstChar) == null){
map.put(firstChar, new ArrayList(Arrays.asList(word)));
}
else{
map.get(firstChar).add(word);
}
}
System.out.println(map + "\n");
if (map.containsKey(String.valueOf(match.charAt(0)))){
System.out.println("GOT KEY");
if (map.containsValue(match)){
System.out.println("GOT VALUE");
}
}
}
最佳答案
一个Map
每个键只能有一个值。要解决此问题,您可以创建 Map<Character, List<String>>
而不是Map<Character, String>
。 Java 8 允许您在一条语句中非常优雅地完成此操作:
Map<Character, List<String>> map =
Files.lines(Paths.get("wordsEn.txt"))
.collect(Collectors.groupingBy(s -> s.charAt(0)));
关于Java Map 读取文件存储在 Map 中的第一个字母作为单词的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39975779/