Java 将多个字符串映射到一个值

Java 将多个字符串映射到一个值,java,constructor,hashmap,Java,Constructor,Hashmap,我有一个构造函数,它将文本文件中单词的第一个字母映射到所有以该字母开头且长度超过3个字符的单词 protected WordStore(String file){ try (BufferedReader br = Files.newBufferedReader(Paths.get(file))) { this.bigMap = br.lines().filter(line -> line.length() > 3).collect(Collectors.g

我有一个构造函数,它将文本文件中单词的第一个字母映射到所有以该字母开头且长度超过3个字符的单词

 protected WordStore(String file){
    try (BufferedReader br = Files.newBufferedReader(Paths.get(file))) {
         this.bigMap = br.lines().filter(line -> line.length() > 3).collect(Collectors.groupingBy(s -> s.substring(0, 1)));
    } catch (IOException e) {
           e.printStackTrace();
    }
}
读取文件时,构造器应为每个单词添加该长度内所有适用前缀的映射。
例如,对于前缀长度为3和单词“abacus”, 映射:

  • 算盘
  • ab->算盘
  • 算盘->算盘
应该加上

此外,应忽略长度小于或等于前缀长度的单词

您将如何更改我已有的构造函数,以便它完成此任务?我很确定我应该在构造函数中添加另一个参数来加载最大前缀长度的字典,但是我被卡住了。

这就是你想要的吗

    List<String> testList = Arrays.asList("abckddkd", "abdsdfwer", "acdxdf");
    Map<String, List<String>> resultMap = testList.stream().filter(line -> line.length() > 3)
            .collect(Collector.of(HashMap::new, (map, line) -> {
                IntStream.range(1, 4).forEach(n->{
                    if(map.get(line.substring(0, n))==null) {
                        List<String> list = new ArrayList<>();
                        list.add(line);
                        map.put(line.substring(0, n),list);
                    }else {
                        //handle duplicate here if you want
                        map.get(line.substring(0, n)).add(line);
                    }
                });
            }, (map1, map2) -> {
                throw new UnsupportedOperationException();
            }, new Characteristics[] { Characteristics.IDENTITY_FINISH }));
    System.out.println(resultMap);
List testList=Arrays.asList(“abckddkd”、“abdsdfwer”、“acdxdf”);
Map resultMap=testList.stream().filter(line->line.length()>3)
.collect(Collector.of(HashMap::new,(map,line)->{
IntStream.range(1,4).forEach(n->{
if(map.get(line.substring(0,n))==null){
列表=新的ArrayList();
列表。添加(行);
map.put(line.substring(0,n),list);
}否则{
//如果需要,请在此处处理重复项
map.get(line.substring(0,n)).add(line);
}
});
},(地图1,地图2)->{
抛出新的UnsupportedOperationException();
},新特性[]{Characteristics.IDENTITY_FINISH});
系统输出打印项次(结果映射);
输出:

{a=[abckddkd,abdsdfwer,acdxdf],ab=[abckddkd,abdsdfwer],abd=[abdsdfwer],ac=[acdxdf],abc=[abckddkd],acd=[acdxdf]}


将文本文件的格式添加到问题中,这似乎是相关的。不要使用收集器,请考虑将MAP()或前缀()插入到手动创建的映射中。