CodesJava

Easy learning with example program codes

how to 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.

TreeSet

TreeSet extends AbstractSet and implements the NavigableSet interface. It maintains ascending order for its elements i.e. elements will be in sorted form.

Example

package com.codesjava;
 
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]
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki