EN
Java - add ArrayList into HashSet
0 points
In this article, we would like to show you how to add ArrayList into HashSet in Java.
In this example, we add existing letters
ArrayList to a new alphabet
HashSet in the constructor.
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("B");
10
letters.add("C");
11
12
Set<String> alphabet = new HashSet<>(letters);
13
14
System.out.println(alphabet);
15
}
16
}
Output:
xxxxxxxxxx
1
[A, B, C]
In this example, we add existing letters
ArrayList to the existing alphabet
HashSet using addAll()
method.
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
Set<String> alphabet = new HashSet<>();
7
8
alphabet.add("A");
9
alphabet.add("B");
10
alphabet.add("C");
11
12
List<String> letters = new ArrayList<>();
13
14
letters.add("D");
15
letters.add("E");
16
letters.add("F");
17
18
alphabet.addAll(letters);
19
20
System.out.println(alphabet);
21
}
22
}
Output:
xxxxxxxxxx
1
[A, B, C, D, E, F]