You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Apache PatriciaTrie实现前缀匹配的多结果推荐列表功能

没问题,这个需求完全可以实现!Apache PatriciaTrie本身就提供了获取所有前缀匹配条目的能力,咱们直接修改代码就能达成目标:

修改后的完整代码

@Override
public Response<List<ChannelSuggestionDTO>> getChannelSuggestion(SubSourceRequest request) {
    // 假设suggestions是已初始化好的PatriciaTrie<Double>实例
    suggestions.put("ronak", 100.0);
    suggestions.put("ronald", 90.0);
    suggestions.put("robert", 200.0);
    suggestions.put("bat", 44.0);
    suggestions.put("batman", 440.0);

    // 获取所有前缀匹配的键值对集合,替代原来的单个select方法
    SortedMap<String, Double> prefixMatches = suggestions.prefixMap(request.getName());

    List<ChannelSuggestionDTO> suggestionDTOList = new ArrayList<>();
    // 遍历所有匹配条目,转换为需要的DTO对象
    for (Map.Entry<String, Double> entry : prefixMatches.entrySet()) {
        ChannelSuggestionDTO channelSuggestionDTO = new ChannelSuggestionDTO();
        channelSuggestionDTO.setName(entry.getKey());
        channelSuggestionDTO.setPriority(entry.getValue());
        suggestionDTOList.add(channelSuggestionDTO);
    }

    // 即使无匹配结果也返回空列表,保证接口健壮性
    return new Response<>(suggestionDTOList);
}

关键改动说明

  • 替换核心方法:用prefixMap(request.getName())替代原来的select(request.getName())。prefixMap()会返回一个SortedMap,包含所有以输入前缀开头的键值对,完美满足多结果推荐的需求。
  • 遍历转换逻辑:通过遍历匹配到的所有条目,逐个转换为ChannelSuggestionDTO对象并加入结果列表,确保所有符合前缀的结果都能被返回。
  • 空场景处理:如果没有任何前缀匹配的条目,prefixMap()会返回空的SortedMap,最终结果列表为空,避免了空指针异常,让接口更稳定。

比如当输入前缀"r"时,prefixMap()会返回包含"ronak"、"ronald"、"robert"三个条目的map,最终接口就会返回这三个对象组成的列表啦。

内容的提问来源于stack exchange,提问作者Dolphin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 06:42:37