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

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

1 comments:

Javin @ arraylist java tutorial July 5, 2011 at 5:23 AM  

Thanks for commenting on my blogpost How to convert arraylist to array with example . I see you also have lots of good content, by the way how are you displaying code with syntax highlighted ?

Thanks
Javin
Why wait() and notify() method must be called from synchronized context

Post a Comment

Related Posts Plugin for WordPress, Blogger...

Random Posts

JavabynataraJ - Find me on Bloggers.com Find me on blorner.com Technology Blogs JavabynataraJ Backlinks Blogarama - The Blog Directory

  © Blogger template Webnolia by Ourblogtemplates.com 2009

Back to TOP