Remove duplicate elements: Difference between revisions

Line 2,955:
<syntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.ArraysIterator;
import java.util.HashSetLinkedHashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
</syntaxhighlight>
One way would be to add the values to a ''Set'' object, which only allows for unique values.
<syntaxhighlight lang="java">
int[] removeDuplicates(int[] values) {
void removeDuplicatesA() {
/* generateuse 20a randomLinkedHashSet integers,to 1 topreserve 4order */
RandomSet<Integer> randomset = new RandomLinkedHashSet<>();
for (int[] arrayvalue =: new int[20];values)
for (int index = 0; index < 20; index++)
array[index] = random.nextInt(1, 5);
System.out.println("before, " + Arrays.toString(array));
/* add the array to a set */
Set<Integer> set = new HashSet<>();
for (int value : array)
set.add(value);
System.out.println("after,values "= +new int[set.size()];
SetIterator<Integer> setiterator = new HashSet<>set.iterator();
for (int index = 0; index < 20; index++)
while (iterator.hasNext())
arrayvalues[index++] = randomiterator.nextIntnext(1, 5);
return values;
}
</syntaxhighlight>
 
Alternately, you could simply add the values to a mutable ''List'', checking if the list already contains the value before adding it.
void removeDuplicatesB() {
<syntaxhighlight lang="java">
/* generate 20 random integers, 1 to 4 */
int[] removeDuplicates(int[] values) {
Random random = new Random();
int[]List<Integer> arraylist = new int[20]ArrayList<>();
for (int indexvalue =: 0; index < 20; index++values)
array[index] = random.nextInt(1, 5);
System.out.println("before, " + Arrays.toString(array));
/* add values to a mutable list */
List<Integer> list = new ArrayList<>(array.length);
for (int value : array)
if (!list.contains(value)) list.add(value);
System.out.println("after,values "= +new int[list.size()];
int index = 0;
for (int value : arraylist)
arrayvalues[index++] = random.nextInt(1, 5)value;
return values;
}
</syntaxhighlight>
<pre>
before[2, [1, 4, 31, 41, 3, 21, 13, 1, 14, 23, 42, 43, 4, 13, 12, 42, 3, 13, 4, 23]
after[2, [1, 24, 3, 4]
 
before, [2, 4, 41, 4, 1, 4, 13, 1, 2, 41, 3, 14, 34, 34, 34, 2, 31, 21, 2, 43, 32]
after, [2, 4, 1, 3]
</pre>
<br />
118

edits