How to use Iterator, for and foreach-loop in Java

Here is a very good example on how to use the Iterator, for and foreach-loop in Java:

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class JavaApplication {
 
  public static void main(String[] args) throws IOException {
    List<String> names = new ArrayList<>();
    names.add("Benny");
    names.add("Sarah");
    names.add("Daniel");
    names.add("Maria");
 
    // Iterator
    Iterator<String> iterator = names.iterator();
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
 
    // for
    for (int i = 0; i < names.size(); i++) {
      System.out.println(names.get(i));
    }
 
    // foreach
    for (String name : names) {
      System.out.println(name);
    }
  }
}

For and foreach loop example in Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static void main(String[] args)
{
  String[] firstNames =
  {
    "Marge", "Homer", "Lisa", "Bart", "Maggie"
  };
 
  System.out.println("- With for loop:");
 
  for (int i = 0; i < firstNames.length; i++)
  {
    System.out.println(firstNames[i]);
  }
 
  System.out.println("- With foreach loop");
 
  for (String name : firstNames)
  {
    System.out.println(name);
  }
}

How to count occurrences of a character in a String with Java?

Code sample:

public class CharacterCounter
{
  public static int countOccurrences(String find, String string)
  {
    int count = 0;
    int indexOf = 0;
 
    while (indexOf > -1)
    {
      indexOf = string.indexOf(find, indexOf + 1);
      if (indexOf > -1)
        count++;
    }
 
    return count;
  }
}

Method call:

int occurrences = CharacterCounter.countOccurrences("l", "Hello World.");
System.out.println(occurrences); // 3

You can also count the occurrences of characters in a string by using the Apache commons lang library with the following one-liner:

int count = StringUtils.countMatches("a.b.c.d", ".");

If you are using the Sping Framework then you can do:

int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");

If you want to be really smart (and don’t want to use a loop), then you can also use this one here:

int count = string.length() - string.replace(find, "").length();