java find duplicates in array
Example 1 Using Loops
- Check for every array element is repeated or not using nested for-loops.
public class main { public static boolean chkForDup(String[] arr) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { if (arr[i].equals(arr[j]) && i != j) { return true; } } } return false; } public static void main(String[] args) { String[] grps = { "one", "two", "three", "one" }; boolean result = chkForDup(grps); System.out.println(result); } }
The Above Code Outputs the
// true
Exmaple 2: Using HashSet
import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class main { public static List < Integer > findDuplicates(int[] nums) { List < Integer > duplicateVal = new ArrayList < > (); HashSet < Integer > set = new HashSet < Integer > (); for (int val: nums) { if (!set.add(val)) { duplicateVal.add(val); } } return duplicateVal; } public static void main(String[] args) { int[] arr = new int[] { 1, 2, 3, 4, 2, 7, 8, 8, 3, 7 }; List < Integer > duplicatesVal; duplicatesVal = findDuplicates(arr); for (Integer val: duplicatesVal) { System.out.print(val + " "); } } }
The Above Code Outputs the
// 2 8 3 7