,java,arrays,arraylist,pattern-matching"/>

首页 > 解决方案 > 在 ArrayList 中搜索单词并将结果保存到地图

问题描述

我在 a 中有一些单词,List<String>我想在 a 中进行迭代ArrayList<String>,搜索匹配项并将它们中的每一个(以及它们的出现)放在 a 中Map<String, Integer>。我写了这个方法:

public Map<String, Integer> findTheWords(ArrayList<String> textInFiles, List<String> words) {


        for (int i = 0; i < textInFiles.size(); i++) {

            Map<String, Integer> mapResult = new HashMap<>();

            for (int j = 0; j < words.size(); j++) {

                    int count = 0;

                    Pattern regexp = Pattern.compile("\\b" + words.get(j) + "\\b");
                    Matcher matcher = regexp.matcher(textInFiles.get(i));

                     if(matcher.find()) {
                         while (matcher.find()) {
                            count++;
                        }

                        mapResult.put(textInFiles.get(i), count);
                     }

            }
        }

    return mapResult;               
    }

问题在于count变量并在地图中插入正确的值

标签: javaarraysarraylistpattern-matching

解决方案


当你这样做时matcher.find(),你正在消耗一个事件。

你有两个解决方案:

1)插入时添加一个,这不是很干净和可读

2)插入前测试

int count = 0;
while (matcher.find()) {
     count++;
}
if (n>0) mapResult.put(textInFiles.get(i), count);

推荐阅读