Duplicate values in an array

The program is about finding the duplicate values inside an array. Here, we are adding all the values of the array to a map and check if the  value is already existing in the map. If the get count of map is equal to 2, the value will be added to a set. Finally the set which contains all the duplicate values will be returned to the main function.

The program is as shown below:


package com.programs;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/*
 * Java program to print duplicate elements in an array
 */

public class dupList {

 public static void main(String args[])

 {

  int arr[] = { 1, 6, 4, 4, 4, 3, 6, 7, 2, 2, 9, 0, 13, 12, 1, 0, 4, 13,
    7 };

  Set<Integer> bset = new HashSet<Integer>();

  bset = returndup(arr);

  System.out.println(" The list of duplicate elements are as follows..");

  for (Integer i : bset)

  {

   System.out.print(i + "  ");

  }

 }

 public static Set<Integer> returndup(int arr[])

 {

  int len = arr.length;

  Map<Integer, Integer> map1 = new HashMap<Integer, Integer>();

  Set<Integer> set = new HashSet<Integer>();

  for (int i = 0; i < len; i++)

  {

   if (map1.containsKey(arr[i]))

   {

    map1.put(arr[i], map1.get(arr[i]) + 1);

   }

   else

   {

    map1.put(arr[i], 1);

   }

   if (map1.get(arr[i]) == 2)

   {

    set.add(arr[i]);

   }

  }

  return set;

 }

}

The output of this program is as follows:

The list of duplicate elements are as follows..
0  1  2  4  6  7  13

Similar Programs:

1) Foreach method in Java 8
2) Program to convert mobile number pad to characters
3) Program to find whether a number is power of 2

Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++