Remove duplicate entries from an array in java

Simplest way to remove duplicate entries from an array is to pass array entries to the TreeSet constructor.

Syntax:

new TreeSet(tmpList);

Example

package com.w3spoint;
 
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
 
public class Test {	 
    public static void main(String[] args) {
    	//Create String Array
    	String[] strArray = {"Jai", "Mahesh", "Hemant", "Hemant", "Mahesh"};
 
    	//Convert String Array to list
        List<String> tmpList = Arrays.asList(strArray);
 
        //Create a TreeSet with the list and eliminates duplicates
        TreeSet<String> treeSet = new TreeSet<String>(tmpList);
        //Print the TreeSet
        System.out.println(treeSet);
    }
}

Output

[Hemant, Jai, Mahesh]
Content Protection by DMCA.com
Please Share