Reputation: 13
I was asked to write a code, which indicates, whether an integer array has duplicate elements or not. This is what I have so far:
int[] input = {1, 2, 3, 4, 1};
boolean hasDuplicates = false;
for (int i = 0; i < input.length; i++) {
for (int j = i + 1; j < input.length; j++) {
if (input[i] != input[j]) {
hasDuplicates = false;
} else if (input[i] == input[j]) {
hasDuplicates = true;
}
}
}
However, this code does not work as it was intended to be, because hasDuplicates
is always false
.
Upvotes: 1
Views: 787
Reputation: 11080
Using Java 8 Streams, stopping on the first found duplicate, a one-liner:
int[] input = {1, 2, 3, 4, 1};
boolean hasDuplicates = !(Arrays.stream(input).allMatch(new HashSet<>()::add))
Upvotes: 0
Reputation: 347
Java 8+ makes life easier. here you go
int[] input = {1, 2, 3, 4, 1};
boolean hasDuplicates = false;
if(Arrays.stream(input).distinct().count() != input.length)
hasDuplicates=true;
System.out.println(hasDuplicates);
Upvotes: 1
Reputation: 4089
You can also iterate over the array once if you use a HashSet. If the add() returns false then we know we have seen that number before.
int[] input = {1, 2, 3, 4, 1};
boolean hasDuplicates = false;
HashSet<Integer> duplicateSet = new HashSet<>();
for (int i = 0; i < input.length; i++) {
if(!duplicateSet.add(Integer.valueOf(input[i])))
{
hasDuplicates = true;
break;
}
}
return hasDuplicates;
Upvotes: 3
Reputation: 63
You can take the benefit of Set data-structure as well:
int[] input = {1, 2, 3, 4, 1};
boolean hasDuplicates = false;
Set<Integer> set = new HashSet<>(input.length);
for (int i : input) {
if (set.add(i)) {
hasDuplicates = false;
}
else {
hasDuplicates = true;
break;
}
}
Set add(E e) returns true if this set did not already contain the specified element.
In a short way:
int[] input = {1, 2, 3, 4, 1};
boolean hasDuplicates = false;
Set<Integer> set = new HashSet<>(input.length);
for (int i : input) {
if (!set.add(i)) {
hasDuplicates = true;
break;
}
}
Upvotes: 1
Reputation: 54148
Once you have decided that the array hasDuplicates
, you may never change that; you can't make disappear the duplicate after. Also use break
the loop, at the moment hasDuplicates
becomes true
int[] input = {1, 2, 3, 4, 1};
boolean hasDuplicates = false;
for (int i = 0; i < input.length; i++) {
for (int j = i + 1; j < input.length; j++) {
if (input[i] == input[j]) {
hasDuplicates = true;
break;
}
}
if (hasDuplicates)
break;
}
Even easier in a method, directly use return
static boolean hasDup(int[] input) {
for (int i = 0; i < input.length; i++)
for (int j = i + 1; j < input.length; j++)
if (input[i] == input[j])
return true;
return false;
}
Upvotes: 3