Write a Java program how to Convert a ArrayList to HashSet


This Java program converts an ArrayList of strings into a HashSet of strings. Here's how the code works:

  • First, an ArrayList named col_list is created and several strings are added to it using the add() method.
  • The size of the ArrayList is printed using the size() method.
  • The ArrayList is then converted to a HashSet named col_set using the HashSet constructor that takes an existing collection as an argument.
  • The size of the HashSet is printed using the size() method.
  • The HashSet is printed using the toString() method, which is implicitly called when an object is passed to System.out.println().
  • The output shows the ArrayList and HashSet before and after the conversion, along with their sizes.

Note that the conversion from ArrayList to HashSet removes any duplicate elements in the list and also changes the order of elements since HashSet does not maintain the order of elements.

Source Code

import java.util.ArrayList;
import java.util.HashSet;
public class Convert_HashSet
{
	public static void main(String args[])
	{
		ArrayList col_list = new ArrayList();
		col_list.add("Blue");
		col_list.add("Green");
		col_list.add("Pink");
		col_list.add("Black");
		col_list.add("Red");
		col_list.add("orange"); 
		col_list.add("White"); 
		System.out.println("Before Converstion of ArrayList...");
		System.out.println("Given Array List :"+col_list);
		System.out.println("Size of ArrayList : " + col_list.size());
 
		//Convert ArrayList to HashSet
		HashSet col_set = new HashSet(col_list);
 
		System.out.println("\nAfter Converstion of HashSet...");
		System.out.println("Size of HashSet : " + col_list.size());
		System.out.println("Given HashSet : "+col_set);
	}
}

Output

Before Converstion of ArrayList...
Given Array List :[Blue, Green, Pink, Black, Red, orange, White]
Size of ArrayList : 7

After Converstion of HashSet...
Size of HashSet : 7
Given HashSet : [Red, orange, Pink, White, Blue, Black, Green]

Example Programs