How to Convert List to Set in Java with Example

How to copy objects from List to Set in Java
Many times we need to copy contents from one collection to other in Java like from List to Set or Set to List. Thanks to Collection framework in Java, copying collection from one to other is extremely easy. Since every Collection class implements Collection interface which defines addAll() method, which can be used to create a collection from contents of another collection. In this Java tutorial we will see example of how to copy contents from List to Set in Java as part of copying data from one collection to other in Java. This is actually nice way to convert List to Set in Java. You can use this technique to convert any List implementation to Set in Java.

Copy Objects from one Collection to Other in Java – Example

Java collection tuorial - copy object from List to Set in javaIn this example we will copy objects from ArrayList to HashSet in Java. This example is just a demonstration by using this technique you can copy elements from one collection to other doesn't matter whether its an ArrayList, LinkedList or HashSet in Java.

package example;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

 * Java program example to copy object from one Collection to another Collection in Java
 * You can copy data from List to Set using addAll() method or you can create copy of collection
 * by passing another Collection like ArrayList to its constructor while creating.
 * @author Javin Paul

public class CollectionTest {
    public static void main(String args[]) throws InterruptedException{            
     List<String> teams = Arrays.asList("India" , "Australia" , "England", "Pakistan");
     System.out.println("Original List: " + teams);
     //copying contents form List to Set in Java ,
     //remember this will remove duplicates from collection because List support duplicates but

     //Set does not support duplicates in Java
     Set<String> cricketTeams = new HashSet<String>(teams);
     System.out.println("Copy collection :" + cricketTeams);

Original List: [India, Australia, England, Pakistan]
Copy collection :[Pakistan, England, Australia, India]

In this example both collection i.e. List and Set will print same values because there is no duplicates. Size of both List and Set will also be same. Only order of both collections will be different because Set doesn't guarantee any ordering while List keeps elements in the order they are inserted into List in Java, that’s why List is also called as ordered collection while Set is known as unordered collection in Java. Now you should not forget how to copy objects from one collection to another in Java, including List to Set or Set to List, just use addAll() or pass collection to constructor while creating copy.

No comments:

Post a Comment