Java Data Type How to - Remove duplicate strings from and ArrayList of Strings








Question

We would like to know how to remove duplicate strings from and ArrayList of Strings.

Answer

/* w ww  . java2  s  .  c om*/
public class Main {

  public static void main(String[] args) {
    String string = "java 2s.com java";
    int length = string.length();
    if (length < 2) {
      System.out.println(string);
      return;
    }

    System.out.print(string.charAt(0));
    for (int i = 1; i < length; i++) {
      if (string.charAt(i) != string.charAt(i - 1)) {
        System.out.print(string.charAt(i));
      }
    }
  }
}