Collection object has a constructor that accept a Collection object to initial the value. Since both Set and List are extend the Collection, the conversion is quite straightforward. It’s just pass a List into Set constructor or vice verse.
List to Set in Java
List to Set in Java
Given a list (ArrayList or LinkedList), convert it into a set(HashSet or TreeSet) of strings in Java.
Method
1 (Simple)
We simply create an list. We traverse the given set and one by one add elements to the list.
We simply create an list. We traverse the given set and one by one add elements to the list.
// Java program to demonstrate conversion of
// list to set using simple traversal
import java.util.*;
class Test {
public static void main(String[]
args)
{
// Creating a
list of strings
List<String>
aList = Arrays.asList("lea", "for",
"learnhowtocode", "learnhowtocode.info", "GFG");
Set<String>
hSet = new HashSet<String>();
for (String x :
aList)
hSet.add(x);
System.out.println("Created
HashSet is");
for (String x : hSet)
System.out.println(x);
// We can created
TreeSet same way
}
}
Method
2 (Using HashSet or TreeSet Constructor)
Method
3 (Using addAll method)
Method 4 (Using stream in Java)
We
use stream in Java to convert given list to stream, then stream to
set. This works only in Java 8 or versions after that.
|
0 comments:
Post a Comment