简体   繁体   English

在 ArrayList 中搜索单词<String>并将结果保存到 Map<String, Integer>

[英]Search for words in a ArrayList<String> and save result to Map<String, Integer>

I have some words in a List<String> and I want to iterate inside an ArrayList<String> , searching for matches and putting each of them (with their occurrences) in a Map<String, Integer> .我在List<String>有一些单词,我想在ArrayList<String>迭代,搜索匹配项并将它们中的每一个(以及它们的出现)放在Map<String, Integer> I write this method:我写这个方法:

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;               
    }

Problem is with count variable and inserting right value in the map问题在于count变量并在地图中插入正确的值

When you do matcher.find() , you're consuming an occurrence.当您执行matcher.find() ,您正在消耗一个事件。

You have two solutions:您有两种解决方案:

1) adding one when inserting, which isn't really clean and readable 1)插入时加一个,不是很干净可读

2) test before you insert 2)插入前测试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM