Your problems
- You are comparing
i
instead of array[i]
.
- You are parsing the
array twice hence every value gets displayed at least once, even if
it is not a duplicate.
This would work but it still prints several times duplicate values:
int array[] = {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13,13};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[i] == array[j] && i != j){
System.out.println(array[i]);
}
}
}
Now, I show you different styles to solve this problem.
A better solution in imperative style.
You are parsing the array n
times which is useless. Provided that the array is sorted (you can sort it anyway), you can compare an element to the next one like in this solution :
int array[] = {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13};
//Optionally
Arrays.sort(array);
Integer last = null;
for(int i = 0; i < array.length -1 ; i++) {
if(array[i] == array[i+1] && (last == null || !last.equals(array[i]))) {
System.out.println(array[i]);
last = array[i];
}
}
I think that this is the most efficient solution but not the most readable.
Another solution with a foreach loop
Unless you explicitly need to access the index of the current element, using a plain old for
loop is evil because it introduces the unecessary variable i
which pollutes the readability of the code.
You can prefer using a foreach statement :
int array[] = {1,2,3,3,3,4,5,6,6,7,8,8,10,10,11,12,13,13};
Set<Integer> uniqueValues = new HashSet<>();
Set<Integer> alreadyDisplayed = new HashSet<>();
for(Integer value : array) {
if(uniqueValues.contains(value) && !alreadyDisplayed.contains(value)) {
System.out.println(value);
alreadyDisplayed.add(value);
}
uniqueValues.add(value);
}
A better solution in functional style.
This solution which is more Java8-friendly :
int array[] = {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13};
//Count occurrences of each number
Map<Integer, Integer> map = new HashMap<>();
Arrays.stream(array).forEach(value -> {
Integer occurrences = map.get(value);
map.put(value, occurrences == null ? 1 : occurrences +1);
});
//Display number of occurrences when nbOccurrences > 1
map.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1)
.forEach(entry -> System.out.println(entry.getKey() + " : "+entry.getValue()));
Note that it also gives the number of occurrences for each value. If you don't need them, you can shorten the code like in previous solutions.
A funnier solution in logical style.
Integer array[] = {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13};
//Convert the array to a list.
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//Use a Set in order to build the collection of unique values.
Set<Integer> uniqueValues = new HashSet<>(list);
//Remove each unique value once from the original list.
uniqueValues.stream().forEach(list::remove);
//Re-compute unique values of the resulting list and display them.
new HashSet<>(list).forEach(System.out::println);