Remove duplicate elements: Difference between revisions

(add RPL)
Line 2,952:
 
=={{header|Java}}==
There is more than 1 way to achieve this. The most logical approach will depend on your application.<br />
<syntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
</syntaxhighlight>
<syntaxhighlight lang="java">
void removeDuplicatesA() {
/* generate 20 random integers, 1 to 4 */
Random random = new Random();
int[] array = new int[20];
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, " + set);
}
 
void removeDuplicatesB() {
/* generate 20 random integers, 1 to 4 */
Random random = new Random();
int[] array = new int[20];
for (int index = 0; index < 20; index++)
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, " + list);
}
</syntaxhighlight>
<pre>
before, [1, 4, 3, 4, 3, 2, 1, 1, 1, 2, 4, 4, 4, 1, 1, 4, 3, 1, 4, 2]
after, [1, 2, 3, 4]
 
before, [2, 4, 4, 4, 4, 1, 1, 2, 4, 3, 1, 3, 3, 3, 2, 3, 2, 2, 4, 3]
after, [2, 4, 1, 3]
</pre>
<br />
Alternate approaches
{{works with|Java|1.5}}
<syntaxhighlight lang="java5">import java.util.*;
118

edits