In: Computer Science
The aim of this lab is to learn the way of converting an ARRAY to a SET and the other way around. To complete this lab we need to remember the implementation of the Set Interface, HashSet Class, and Arrays.
Java code for your requirements given below,
Java program:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class ArrayToSet
{
public static void main(String aa[])
{
String courses[]= {"cse","ece","eee","it","mech"};
//Convert using asList method
Set<String> set = new
HashSet<String>(Arrays.asList(courses));
System.out.println(set);
//Convert using stream
Set<String> set1=
Arrays.stream(courses).collect(Collectors.toSet());
System.out.println(set1);
}
}
Output should be displaying like this,
Note:
I printed set objects directly, If u want to print set values one by one use Iterator like this,
Iterator value=set.iterator();
while(value.hasNext())
{
System.out.println(value.next());
}