Find duplicate value array

Find duplicate value array

Below is java program which will find duplicate value in array. We have tested it with two operation:

  • checkDuplicateTraditionalWay – This method find duplicate using traditional logic without using API
  • checkDuplicateUsingSet – This method find duplicate using Set interface
package com.javahonk.duplicate;

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

public class FindDuplicate {

    public static void main(String[] args) {

        String[] value = new String[5];
        value[0] = "Java";
        value[1] = "Java";
        value[2] = "Honk";
        value[3] = "Honk";
        value[4] = "Duplicate";

        System.out.println("Origional Array value:");
        for (int i = 0; i < value.length; i++) {
            if (null != value[i]) {
                System.out.print(value[i] + " ");
            }

        }

        checkDuplicateTraditionalWay(value);

        checkDuplicateUsingSet(value);

    }

    /**
     * @param value
     */
    public static void checkDuplicateUsingSet(String[] value) {
        System.out
                .println("\n\nExample 2:\nCheck duplicate using"
                        + " set. Below are duplicate value in array");

        Set<String> set = new HashSet<String>();
        for (String string : value) {
            if (set.contains(string))
                System.out.println(string);
            else if (null != string && !string.equals(""))
                set.add(string);
        }
    }

    /**
     * @param value
     */
    public static void checkDuplicateTraditionalWay(String[] value) {
        Boolean duplicate = false;

        List<String> dupList = new ArrayList<String>();
        for (int i = 0; i < value.length; i++) {
            String string = value[i];
            int k = 0;
            for (int j = 0; j < value.length; j++) {
                String string2 = value[j];
                if (null != string && string.equalsIgnoreCase(string2)) {
                    k++;
                    if (k > 1) {
                        dupList.add(string);
                        duplicate = true;
                    }

                }

            }
        }

        System.out
                .println("\n\nExample 1: \nCheck duplicate "
                        + "using tradiional way:\n");

        System.out.println("Array contains duplicate: " + duplicate);
        System.out.println("Duplicate value in array: " + dupList);
    }

}

 

Output:

Find duplicate value array

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *