CodesJava

Easy learning with example program codes

how to find duplicate value in an array in java?


Simplest way to find duplicate entries in an array is to add array entries to the TreeSet. As treeset does not support duplicate entries, we can easily find out duplicate entries.

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.TreeSet;
 
public class Test {	 
    public static void main(String[] args) {
    	//Create String Array
    	String[] strArray = {"Jai", "Mahesh", "Hemant", "Hemant", "Mahesh"};
 
    	//Create TreeSet Object
    	TreeSet<String> treeSet = new TreeSet<String>();
    	System.out.println("Duplicate Entries: ");
    	for(String string:strArray){
            if(!treeSet.add(string)){
                System.out.println(string);
            }
        }
    }
}

Output

Duplicate Entries: 
Hemant
Mahesh
Sign Up/ Sign In
Ask a Question


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