找到数组列表中字符串出现次数

时间:2017-05-21 16:51:17

标签: java arraylist

我有数组列表,我想查找java中列表中字符串出现次数。

假设数组列表有

[ {"ev":"Description","iv":"...","id":"1"}, {"ev":"Surface","iv":"...","id":"2"}, {"ev":"Locals","iv":"...","id":"3"} ]

我想得到每次出现的次数

1 个答案:

答案 0 :(得分:1)

你的问题不是很明确。预期产量到底是什么?您想要自己计算每个列表的出现次数吗?

通常,您会使用Map来计算出现次数。与HashMap一样,它们允许快速访问。

这是一个小片段,可以计算给定文字的所有单词出现次数:

final String input = "word word test word";
// Splits at word boundary
final String[] words = input.split("\\b");

final HashMap<String, Integer> wordToCount = new HashMap<>();
// Iterate all words
for (final String word : words) {
    if (!wordToCount.contains(word)) {
        // Word seen for the first time
        wordToCount.put(word, 1);
    } else {
        // Word was already seen before, increase the counter
        final int currentCounter = wordToCount.get(word);
        wordToCount.put(word, currentCounter + 1);
    }
}

// Output the word occurences
for (final Entry<String, Integer> entry : wordToCount.entrySet()) {
    System.out.println("Word: " + entry.getKey() + ", #: " + entry.getValue());
}

此代码段的输出类似于:

Word: word, #: 3
Word: test, #: 1