How to Interconvert List and Set in Java


In this example, let’s  see how to interconvert list and set in Java.

Source Code

1) List To Set

package com.beginner.examples;

import java.util.*;

public class List2SetExample {

	public static void main(String[] args) {

		List list = new ArrayList();  
		list.add("AA");  
		list.add("BB");  
		list.add("CC");  
		list.add("DD");
		
		Set set = new HashSet(list);  
		System.out.println(set); 
    }
}

Output:

[AA, BB, CC, DD]

2) Set To List

package com.beginner.examples;

import java.util.*;

public class Set2ListExample {

	public static void main(String[] args) {

        Set set = new HashSet();  
        set.add("AA");  
        set.add("BB");  
        set.add("CC");
        set.add("DD");

        List list = new ArrayList(set);  
        System.out.println(list);
    }
}

Output:

[AA, BB, CC, DD]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments