Finding Duplicates in Array Using TreeSet Java Example Program


Definition

TreeSet uses a red-black tree implemented by a java.util.TreeMap. The red-black tree makes sure that there are no duplicates. Additionally, it allows TreeSet to implement java.util.SortedSet. Thus TreeSet itself sorts the values in it.

Syntax

TreeSet<variable-type> variableName = new TreeSet<variable-type>();

Example Program

import java.util.Arrays;
import java.util.TreeSet;

public class DuplicatesInArrayUsingTreeSet {

    public static void main(String[] args) {
        String[] array = new String[]{"a", "d", "z", "x", "t", "b", "a", "z"};
        System.out.println("Input Array is : " + (Arrays.toString(array)));
        TreeSet<String> treeSet = new TreeSet<String>();
        for (String str : array) {
            if (!treeSet.add(str)) {
                System.out.println("Duplicate Entry is: " + str);
            }
        }
        System.out.println("TreeSet is : " + treeSet);
    }
}

Sample Output

Input Array is : [a, d, z, x, t, b, a, z]
Duplicate Entry is: a
Duplicate Entry is: z
TreeSet is : [a, b, d, t, x, z]