How to Interconvert Set and Array in Java


In this example we will show the method to interconvert set and array in Java.

Source Code

1) Set To Array

package com.beginner.examples;

import java.util.*;

public class Set2ArrayExample {

	public static void main(String[] args) {

		Set set = new HashSet();  
        set.add("AA");  
        set.add("BB");  
        set.add("CC");
        set.add("DD"); 
          
        Object[] obj = set.toArray();
		System.out.println(Arrays.toString(obj));
    }
}

Output:

[AA, BB, CC, DD]

2) Array To Set

package com.beginner.examples;

import java.util.*;

public class Array2SetExample {

	public static void main(String[] args) {

		String[] string=new String[]{"AA","BB","CC","DD"};
		Set set = new HashSet(Arrays.asList(string));    
	    System.out.println(set);
    }
}

Output:

[AA, BB, CC, DD]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments