Reputation: 37
I'm trying to find non-repeating numbers in array and print those numbers to new array. It's kinda working but prints one number twice for some reason and I don't understand why. The output should be 4 and 7 but it prints 4 4 7.
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
public class Frequence {
public static void main(String[] args) {
int[] array = new int[]
{
1, 2, 3, 2, 3, 3, 5, 4, 7, 1, 5
};
List<Integer> arr = new ArrayList<>();
for (int value : array) {
int count = 0;
for (int i : array)
if (value == i)
count++;
if (count == 1) {
arr.add(value);
Integer[] arr2 = new Integer[arr.size()];
arr2 = arr.toArray(arr2);
for (Integer k : arr2)
System.out.println(k);
}
}
}
}
Upvotes: 1
Views: 741
Reputation: 40034
Since you are using a List<>
you might consider using a Set<>
. Since set values don't contain duplicates and their values are hashed they lend themselves to this type of operation.
The following works with a single loop:
nonDups
set.found
set. If this value is already in that set it was
located earlier and returns false. Thus it must be a duplicate so remove it from nonDups
.Set<Integer> nonDups = new HashSet<>();
Set<Integer> found = new HashSet<>();
for (int k : array) {
nonDups.add(k);
if (!found.add(k)) { // returns false if already present
nonDups.remove(k);
}
}
System.out.println(nonDups);
Prints
[4,7]
Upvotes: 3
Reputation: 1281
Your print loop prints the whole arr each time unique element is found so it should be outside the for (int value : array)
loop:
for (int value : array) {
// ...
if (count == 1) {
arr.add(value);
}
}
for (Integer k : arr) {
System.out.println(k);
}
UPD: The simplest approach to find unique element of an array would be using the Set
collection. The whole task can be solved with a one-liner:
Set<Integer> uniques = new HashSet(Arrays.asList(array));
Or if you are OK with unmodifiable collection and use Java 9+:
Set<Integer> uniques = Set.of(array);
Upvotes: 2
Reputation: 3027
I simplified your code and the problem is you are printing inside the first loop:
int[] array = new int[] { 1, 2, 3, 2, 3, 3, 5, 4, 7, 1, 5 };
List<Integer> arr = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = 0; j < array.length; j++) {
if(array[i] == array[j]) {
count++;
}
}
if(count == 1) {
arr.add(array[i]);
}
}
System.out.println(arr.toString());
Upvotes: 0