如何编写映射以便每个单词的首字符映射到整个单词?
考虑包含以下内容的单词列表:
- 阿尔伯特
- 本
- 爱丽丝
- 塞西莉亚
输出应为 {a=[albert,alice], b=[ben], c=[cecilia]}
这就是我现在所拥有的,但我不明白如何将每个键映射到所有对应的单词。
map 类型为 Map<String, List<String>> bigMap;
protected WordStore(String file) {
this.bigMap = new HashMap<>();
String line = "";
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file));)
{
this.wordlist = new ArrayList<String>();
wordlist.add(file);
while ( (line = bufferedReader.readLine()) != null){
bigMap.putIfAbsent(String.valueOf(line.charAt(0)), new ArrayList<>());
}
}
最佳答案
读取所有行并将其添加到 List<String>
。完成后,您可以使用groupingBy
来完成手头的任务。收集器。
this.bigMap = myList.stream()
.collect(Collectors.groupingBy(s -> s.substring(0, 1)));
或者您可以一次性读取文件并将其分组,如下所示:
try (Stream<String> stream = Files.lines(Paths.get(file))) {
this.bigMap = stream.collect(Collectors.groupingBy(s -> s.substring(0, 1)));
} catch (IOException e) {
e.printStackTrace();
}
或者:
try (BufferedReader br = Files.newBufferedReader(Paths.get(file))) {
this.bigMap = br.lines()
.collect(Collectors.groupingBy(s -> s.substring(0, 1)));
} catch (IOException e) {
e.printStackTrace();
}
关于java - 将每个以相同字符开头的键映射到单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48976286/