Johnny
Johnny

Reputation: 17

Count the number of occurrences of keywords in an Array list

public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<String>();
    String s = "nope";
    String v = "nopenopes";
    list.add(s);
    list.add(v);
    keywordCount(list, "nope"); 

}
public static int keywordCount(ArrayList<String> str , String keyword){
    int count = 0;

    for (int i = 0;i<str.size();i++){
    while ((i= str.indexOf(keyword,i)) != -1) { // here is where I found the error
          count++;
          i += keyword.length();    
}}

    System.out.println(count);
    return count;
}

hello, I'm writing a piece of code that counts the occurrences of a specific keyword inside an array list. It worked for a line of string but did not when trying to do the same thing for an arraylist. Can someone please point out what I did incorrectly and help me fix it. Thanks in advance.

Upvotes: 1

Views: 1623

Answers (4)

Easily you can use contains() method;

public static int keywordCount(ArrayList<String> str , String keyword){
    int count = 0;

    for (int i = 0; i<str.size();i++){
        if(str.get(i).contains(keyword)) 
          count++;
    }
}

Upvotes: 2

Yogesh Prajapati
Yogesh Prajapati

Reputation: 4870

use code below.

public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("a");

        // get all Unique keywords 
        Set<String> set = new HashSet<String>(list);
        for(String keyword: set){
            System.out.println(keyword + ": " + Collections.frequency(list, keyword));
        }
    }

Output:

b: 1
a: 2

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201419

You could use Arrays.asList() to construct your List.

public static void main(String[] args) {
  System.out.println(keywordCount(Arrays.asList("nope", "nopenopes"), "nope"));
}

public static int keywordCount(List<String> al, String keyword) {
  int count = 0;
  for (String str : al) {
    int i = 0;
    while ((i = str.indexOf(keyword, i)) != -1) {
      count++;
      i += keyword.length();
    }
  }
  return count;
}

When I run the above I get the output

3

One issue in your code was

i = str.indexOf(keyword,i)

In your post str is not a String, it is an ArrayList.

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

You can sue Collections.frequncy()

 List<String> list=new ArrayList<>();
 list.add("a");
 list.add("b");
 list.add("a");
 System.out.println(Collections.frequency(list,"a")); // out put is 2

Let's say you have a List<String> list then you want to find number of occurrence keyword

Then

int numOfOccurrences= Collections.frequency(list,keyword)

Upvotes: 4

Related Questions