bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/Java/Java How To's
Java•Java How To's

Java How To Find Duplicates in an Array

Find Duplicate Elements in an Array

Print which elements appear more than once:

Example

int[] nums = {1, 2, 3, 2, 4, 5, 1};
for (int i = 0; i < nums.length; i++) {
  for (int j = i + 1; j < nums.length; j++) {
    if (nums[i] == nums[j]) {
      System.out.println("Duplicate: " + nums[i]);
    }
}
}

Explanation: We go through the array one element at a time. - The outer loop picks a number (like the first 1 ). - The inner loop compares it with all the numbers that come after it. - If a match is found, we print it as a duplicate. In this example, the program finds 2 twice and 1 twice, so it prints them as duplicates.

Previous

Java How To - Remove Duplicates from an Array

Next

Java How To - Shuffle an Array