How do I sort items in a Set?

The trick to sort a java.util.Set is to use the implementation of a java.util.SortedSet such as the java.util.TreeSet class. The example below shows you the result of using the java.util.TreeSet class, in which the items in it will be sorted based on the element’s natural order.

package org.kodejava.example.util;

import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {
    public static void main(String[] args) {
        // The TreeSet class is an implementation of a SortedSet, this means
        // that when your are using the TreeSet to store you data collections
        // you'll get the items ordered base on its elements natural order.
        Set<String> set = new TreeSet<String>();

        // In the example below we add some letters to the TreeSet, this mean
        // that the alphabets will be ordered based on the alphabet order
        // which is from A to Z.

        for (String item : set) {
            System.out.print(item + " ");

This demo prints:

A B F H N X Z 

How do I remove duplicate element from array?

This example demonstrates you how to remove duplicate elements from an array using the java.util.HashSet class.

package org.kodejava.example.util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ArrayRemoveDuplicate {
    public static void main(String[] args) {
        // A string array with duplicate values
        String[] data = {
                "A", "C", "B", "D", "A", "B", "E", "D", "B", "C"
        System.out.println("Original array         : " +

        // Convert it to list as we need the list object to create a
        // set object. A set is a collection object that cannot have
        // a duplicate values, so by converting the array to a set
        // the duplicate value will be removed.
        List<String> list = Arrays.asList(data);
        Set<String> set = new HashSet<String>(list);

        System.out.print("Remove duplicate result: ");

        // Create an array to convert the Set back to array.
        // The Set.toArray() method copy the value in the set to the
        // defined array.
        String[] result = new String[set.size()];