EN
Java - remove duplicates from ArrayList using HashSet
0 points
In this article, we would like to show you how to remove duplicates from ArrayList in Java.
Quick solution:
xxxxxxxxxx
1
Set<String> mySet = new HashSet<>(myArrayList);
In this example, we create HashSet from the letters
ArrayList to remove duplicates.
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
List<String> letters = new ArrayList<>();
7
8
letters.add("A");
9
letters.add("A");
10
letters.add("A");
11
12
letters.add("B");
13
letters.add("B");
14
15
letters.add("C");
16
17
Set<String> distinctSet = new HashSet<>(letters); // removes duplicates
18
19
System.out.println(distinctSet);
20
}
21
}
Output:
xxxxxxxxxx
1
[A, B, C]