# Find the first non-repeating element in an integer array [2 ways]

In this post, I will be sharing how to find the first non-repeating element in an Integer array in Java with examples. There are two ways to achieve our goal:

1. Using HashMap [Recommended]

2. Using Nested Loops [Easiest]

Read Also: Find first non-repeated character in string in Java

We will understand the question first with the help of the examples:

``` ```Input: {21, 34, 21, 67, 81, 67};
Output: 34
Explanation: First number that does not repeat is: 34``````

``` ```Input: {1, 2, -3, -3, 1, 2, 4};
Output: 4
Explanation: First number that does not repeat is: 4``````

## Find the first non-repeating element in an integer array

### 1. Using HashMap

We can easily find the first non-repeating element in an integer array using HashMap.

1. The idea is to store the number of times every element appears in the HashMap.
2. Then, traverse the array to find out the first element whose frequency is 1 as the value in the HashMap.

``` ```import java.util.Map;
import java.util.HashMap;

public class FirstNonRepeatingNumber {
public static void main(String args[]) {
// Given array
int[] arr = new int[] {21, 34, 21, 67, 81, 67};
int n = arr.length;
// Creating HashMap object
Map<Integer, Integer> map = new HashMap<>();
// Inserting all elements of array in HashMap
for (int i=0; i < n ;i++)
{
if (map.containsKey( arr[i] ))
{
map.put(arr[i], map.get(arr[i])+1);
}
else
{
map.put(arr[i], 1);
}
}
// Traversing array again and return first element with count=1
for (int i = 0; i < n; i++)
{
if(map.get(arr[i]) == 1)
{
System.out.println("First non-repeating number is: " + arr[i]);
break;
}
}
}
}``````

Output:
First non-repeating number is: 34

### 2. Using Nested Loops

The simplest solution to find the first non-repeating element in an integer array is by using nested loops. We are using two loops.

1. Outer loop traverses the given array.
2. Inner loop checks if the element is present more than once or not.

``` ```public class FirstNonRepeatingNumber2 {
public static void main(String args[]) {
// Given array
int[] arr = new int[] {1, 2, -3, -3, 1, 2, 4};
int n = arr.length;
for (int i = 0; i < n; i++)
{
int j;
// Check if ith element is present in array
for (j = 0; j < n; j++)
{
if(i != j && arr[i] == arr[j])
break;
}
if (j == n)
{
// Print the ith element
System.out.println("First non-repeating number is: " + arr[i]);
break;
}
}
}
}``````

Output:
First non-repeating number is: 4

That's all for today. Please mention in the comments if you have any questions related to how to find the first non-repeating element in an integer array in Java with examples.