11 July, 2019

How to find duplicate elements from array in Java

In this article, we will see how to find the duplicate values from an array or list using java.  This is one of important programming questions in technical interview. Each interviewer has different approach to access the candidate. But, the logic and the approach by candidate is really matter. In this program we have used Map and List both, so its a kind of collections interview questions. You can find few more collection interview question.  Today we will see how to find the duplicate values from array. 


The logic is very simple here, see the below.

  • At first we need we need to create a Map to hold the key-value pair. Where key is the array element and value is the counter for number of time the array element repeats.
  • Then we will iterate the array and put into the map as per the above step. If the map contains the element earlier, then we will update the value +1.
  • Finally we will have the map , which holds the array elements with the counter for repentance. 
  • Now, we will iterate the Map , by checking the condition where the counter is more than 1 (i.e. its duplicated or repeated).


DuplicateFinder.java



package com.javadevelopersguide.lab.basic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
 * This program illustrate to find the duplicate values in a List.
 *
 * @author manoj.bardhan
 *
 */
public class DuplicateFinder {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(4, 3, 5, 25, 25, 25, 13, 5, 22, 4, 90));
System.out.println("List Date = " + list);
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < list.size(); i++) {
if (map.isEmpty()) {
map.put(list.get(i), 1);
} else if (map.containsKey(list.get(i))) {
map.put(list.get(i), map.get(list.get(i)) + 1);
} else {
map.put(list.get(i), 1);
}
}
System.out.println("\nDuplicate values are: ");
// Iterate the Map and display the duplicate values.
for (Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey());
// TODO We can now put these values into any list.
}
}
}
}

Output - 

3 comments:

  1. } else if (map.containsKey(list.get(i))) {
    map.put(list.get(i), map.get(list.get(i)) + 1);

    3 times you should getting from array? Why not variable? ^^

    ReplyDelete