Powered by Blogger.

Can i convert List to Set (or) ArrayList to HashSet ?

>> Friday, June 10, 2011

Yes.We can convert from List to Set.Both are under the same Superclass Collection Interface.So there are more chances to convert.







Actually ArrayList follows the insertion order of elements.When you tried to convert from ArrayList to HashSet it won't preserve the previous order, it may change according to the properties of HashSet.Set won't maintain the order of elements.

Here we are passing the reference of the List to HashSet constructor at the creation of set object.

Set<Object> set = new HashSet<Object>(list);



Q). Why should i convert List to Set ?

A). To eleminate duplicate values and null values in the list.

In our program i have given duplicate values and nulls in list to convert into set.After that it shows with out duplicates.

package javabynatarj.collections;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class ListToSet {
 public static void main(String[] args) {
  
  List<Object> list = new ArrayList<Object>();
  list.add("one");
  list.add("two");
  list.add("three");
  list.add("one");
  list.add(null);
  list.add("four");
  list.add(null);
  System.out.println("The ArrayList Object is:");
  System.out.println(list+"\n");
  
  Set<Object> set = new HashSet<Object>(list);
  System.out.println("The HashSet Object is:");
  System.out.println(set+"\n");
  
  System.out.println("By Iterating the Values of Set");
  Iterator<Object> it  = set.iterator();
  while(it.hasNext()){
   System.out.println(it.next());
  }
 }
}

Output of the above Program:



Reference books:

Java Collections: An Introduction to Abstract Data Types, Data Structures and Algorithms   Data Structures in Java: From Abstract Data Types to the Java Collections Framework

About Author

My Photo
GeekDude
Hi, this is Muralidhar from Chennai.I like blogging on some known things. Trying to provide some basic information for java beginners.
View my complete profile

Random Posts

© javabynataraj.blogspot.com from 2009 - 2014. All rights reserved.