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.
1. Add ArrayList on HashSet creation
In this example, we add existing letters ArrayList to a new alphabet HashSet in the constructor.
import java.util.*;
public class Example {
public static void main(String[] args) {
List<String> letters = new ArrayList<>();
letters.add("A");
letters.add("B");
letters.add("C");
Set<String> alphabet = new HashSet<>(letters);
System.out.println(alphabet);
}
}
Output:
[A, B, C]
2. Add ArrayList to the existing HashSet
In this example, we add existing letters ArrayList to the existing alphabet HashSet using addAll() method.
import java.util.*;
public class Example {
public static void main(String[] args) {
Set<String> alphabet = new HashSet<>();
alphabet.add("A");
alphabet.add("B");
alphabet.add("C");
List<String> letters = new ArrayList<>();
letters.add("D");
letters.add("E");
letters.add("F");
alphabet.addAll(letters);
System.out.println(alphabet);
}
}
Output:
[A, B, C, D, E, F]