Various approaches for Finding Duplicate Numbers in Java 2D Array are discussed here. We will be using Traditional for loop, Set Interface, Map interface using JDK earlier versions, and JDK 8.
Finally, the main program is given to run all the codes.
For loop - Java 1 to 4
Convert the 2D array to a 1D array first and then iterate the integer two dimensional array using for loop
/**
* Find Duplicate using for loop
* @param array input 2D array
* @return Set of duplicateElement
*/
public static Set<Integer> findDuplicatesForLoop(int[][] array) {
Set<Integer> duplicateElement = new HashSet<>();
// flattened 1D array
int[] intArray = Stream.of(array).
flatMapToInt(IntStream::of).toArray();
for (int i = 0; i < intArray.length; i++) {
for (int j = i + 1; j < intArray.length; j++) {
if (intArray[i] == intArray[j]) {
duplicateElement.add(intArray[i]);
}
}
}
return duplicateElement;
}
Using Set - Java 2 to 7
Iterate through the 2D array and first add the unique values to the Set. If the Set already contains the integer values, consider it as duplicates and add it to another Set. Return the duplicate numbers and print them in the console.
/**
* Find duplicate integers by traversing through array and add elements to Set
* @param array
* @return Set of duplicateNumbers
*/
public static Set<Integer> getRepeatingNumbers(int[][] array) {
Set<Integer> set = new HashSet<>();
Set<Integer> duplicateNumbers = new HashSet<>();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (set.contains(array[i][j])) {
duplicateNumbers.add(array[i][j]);
} else {
// add only unique values
set.add(array[i][j]);
}
}
}
return duplicateNumbers;
}
Using Map - Java 2 to 7
Here Duplicate numbers are kept as a key and the recurrence of duplicates is kept as value. If entry.getValue() is greater than one then add the integer key to the list. This will help you to grasp the java 8 map example that is explained in the upcoming example code.
/**
* Find Repeating Integers using Map
* @param array 2dArray
* @return List of duplicateIntegers
*/
private static List<Integer> getRepeatingNumbersMap(int[][] array) {
Map<Integer, Integer> map = new HashMap<>();
List<Integer> duplicateIntegers = new ArrayList<>();
for (int[] row : array) {
for (int col : row) {
if (map.get(col) == null) {
map.put(col, 1);
} else {
map.put(col, map.get(col) + 1);
}
}
}
Set<Entry<Integer, Integer>> entrySet = map.entrySet();
for (Entry<Integer, Integer> entry : entrySet) {
if (entry.getValue() > 1) {
duplicateIntegers.add(entry.getKey());
}
}
return duplicateIntegers;
}
Rewriting the above code for convenience to process with the one dimensional array. Here row is nothing but a flattened array of integers. For flattening alone we are using java 8 and iterating through each array and the map is carried through java 5 enhanced for loop.
/**
* Find Repeating Integers using Map.
* Input 2D Array converted to 1D array for processing
*
* @param array 2D array
* @return List of dulicate integers
*/
private static List<Integer> getRepeatingNumbersMap1D(int[][] array) {
int[] row = Stream.of(array).
flatMapToInt(IntStream::of).toArray();
Map<Integer, Integer> map = new HashMap<>();
List<Integer> duplicateIntegers = new ArrayList<>();
for (int col : row) {
if (map.get(col) == null) {
map.put(col, 1);
} else {
map.put(col, map.get(col) + 1);
}
}
for (Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
duplicateIntegers.add(entry.getKey());
}
}
return duplicateIntegers;
}
The above examples are prior to Java Version 8.
Using Set - Java 8
Add unique numbers first and filter by non unique numbers and then collect the Set of duplicate numbers.
/**
* Java 8 - Find Repeating Integers using Set
* @param array
* @return Set of duplicateNumbers
*/
public static Set<Integer> getRepeatingNumbersJDK18(int[][] array) {
Set<Integer> uniqueNumbers = new HashSet<>();
Set<Integer> duplicateNumbers = Arrays.stream(array)
.flatMapToInt(IntStream::of)
.filter(v -> !uniqueNumbers.add(v))
.boxed()
.collect(Collectors.toSet());
return duplicateNumbers;
}
Using Map - Java 8
Group by duplicate values. Filter the stream by using the recurrence of the duplicate values. Get the key ( duplicate integers) and collect it as a list.
/**
* Java 8 - Find Repeating Integers using Map
*
* @param array
* @return List of duplicateNumbers
*/
public static List<Integer> getRepeatingNumbersJDK18Map(int[][] array) {
List<Integer> duplicateNumbers = Arrays.stream(array)
.flatMapToInt(IntStream::of)
.boxed()
.collect(Collectors.groupingBy(v -> v, Collectors.counting()))
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
return duplicateNumbers;
}
Main class
In this class, we have only provided you with the ways to print duplicate numbers. You can execute the above individual piece of code here. Repeating all the same code again will be considered as code duplication 🙂
package com.digitizedpost.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
class FindDuplicateNumber {
public static void main(String[] args) {
int[][] input = {
{1, 2, 7},
{1, 15, 6, 1, 50},
{3, 9, 0, -2, 3},
{5, 4, 3, 3, 0, -10}
};
System.out.println("Duplicate Numbers: " + getRepeatingNumbersJDK18(input));
System.out.println("Duplicate Numbers: " + getRepeatingNumbersJDK18Map(input));
System.out.println("Duplicate Numbers: " + findDuplicatesForLoop(input));
getRepeatingNumbersMap(input).stream().forEach(e->System.out.print(e + " "));
getRepeatingNumbersMap1D(input).stream().forEach(e->System.out.print(e + " "));
}
//individual code goes here
}
Output
0 1 3
In this post, you have learned about several ways of finding duplicate numbers from a given two dimensional array.