EN
Java - merge two Lists into HashSet
0 points
In this article, we would like to show you how to merge two Lists into the HashSet in Java.
Quick solution:
xxxxxxxxxx
1
Set<String> mySet = new HashSet<>(myArrayList1);
2
mySet.addAll(myArrayList2);
In this example, we merge letters1
and letters2
ArrayLists into alphabet
HashSet using addAll()
method.
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
List<String> letters1 = new ArrayList<>();
7
8
letters1.add("A");
9
letters1.add("B");
10
11
List<String> letters2 = new ArrayList<>();
12
13
letters2.add("C");
14
letters2.add("D");
15
16
Set<String> alphabet = new HashSet<>(letters1);
17
alphabet.addAll(letters2);
18
19
System.out.println(alphabet);
20
}
21
}
Output:
xxxxxxxxxx
1
[A, B, C, D]