Newbie2015Giant Newbie2015Giant - 1 year ago 71
Java Question

How to count the number of elements of an arraylist with a certain term/word?

I have an arraylist of sentences as follows-

List<String> allDocuments= new ArrayList<String>();
list.add("my name is john what is your name");
list.add("hello how are you");
list.add("no name entered");
list.add("who are you");

As you can see in two elements the word 'name' and 'you' appears. How do I get the number of elements each word appears in? so the end result would be

name = 2 elements

my= 1 elements

you=2 elements

So far I'm stuck on the number of times each word appears in a single element instead of how many elements have the each word.

List<String[]> list2 = new ArrayList<>();
for (String s : allDocuments) {
list2.add(s.split(" "));
for (String[] s : list2) {
Map<String, Integer> wordCounts = new LinkedHashMap<String, Integer>();

for (String word : s) {
Integer count = wordCounts.get(word);
if (count == null) {
count = 0;
wordCounts.put(word, count + 1);

for (String key : wordCounts.keySet()) {

System.out.println(key + ": " + wordCounts.get(key));


Would appreciate the help, thanks!

hal hal
Answer Source
Map<String, Integer> wordCounts = new HashMap<String, Integer>();

//making list of all words
for (String s : allDocuments)
  for ( String s2 : s.split(" "))
    if( ! wordCounts.containsKey(s2) )

//counting occurence of all words in whole strings
for (String k : wordCounts.keySet())
  for (String s : allDocuments)
    if(s.indexOf(k) != -1)
      wordCounts.put(k, wordCounts.get(k)+1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download