簡體   English   中英

在 ArrayList 中搜索單詞<String>並將結果保存到 Map<String, Integer>

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

我在List<String>有一些單詞,我想在ArrayList<String>迭代,搜索匹配項並將它們中的每一個(以及它們的出現)放在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變量並在地圖中插入正確的值

當您執行matcher.find() ,您正在消耗一個事件。

您有兩種解決方案:

1)插入時加一個,不是很干凈可讀

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