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 extends AbstractSet and implements the NavigableSet interface. It maintains ascending order for its elements i.e. elements will be in sorted form.


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


[Hemant, Jai, Mahesh]
Please follow and like us:

Copyright © 2019 CodesJava Protection Status SiteMap Reference: Java Wiki