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:
Set<String> mySet = new HashSet<>(myArrayList1);
mySet.addAll(myArrayList2);
Practical example
In this example, we merge letters1 and letters2 ArrayLists into alphabet HashSet using addAll() method.
import java.util.*;
public class Example {
public static void main(String[] args) {
List<String> letters1 = new ArrayList<>();
letters1.add("A");
letters1.add("B");
List<String> letters2 = new ArrayList<>();
letters2.add("C");
letters2.add("D");
Set<String> alphabet = new HashSet<>(letters1);
alphabet.addAll(letters2);
System.out.println(alphabet);
}
}
Output:
[A, B, C, D]