Java Collection -Set

<I>Set

does not contain duplicates.

randomly stores elements.

does not permits null elements.

How to make your list synchronised?

Collections.synchronizedSet(yourSetObject)

Classes 

<C>TreeSet

Sorts element by natural order.

rest of the properties are same as specified by interface Set

Internally it is implemented using the TreeMap.

       Main purpose is for sorting the stores elements.

        Treeset sorts the element by default using the custom order.

          If you want the items stored in element to be stored by their age name or address you can use comparator.

How to create TreeSet

Set<String> setObj=new TreeSet<>();

How to add element in treeset?

setObj.add(“zone”);

How to remove?

setObj.remove(“zone”);

How to traverse the TreeSet?

same as we have done before use Iterator

Iterator<String> it=treeMapObj.iterator();
while(it.hasNext())

{

System.out.println(“Value=>”+it.next());

}

}

Complete Program

package com.collection;
import java.util.Iterator;

import java.util.Map;

import java.util.Set;

import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {

Set<String> setObj=new TreeSet<>();

setObj.add(“zone”);

setObj.add(“zoo”);

setObj.add(“bajuka”);

setObj.add(“jzoo”);

setObj.add(“azoo”);

setObj.remove(“zone”);

setObj.add(null);
iterateAndPrint(setObj);

}

public static void iterateAndPrint(Set treeMapObj)

{
Iterator<String> it=treeMapObj.iterator();
while(it.hasNext())

{

System.out.println(“Value=>”+it.next());

}

}
}


Output

Value=>azoo

Value=>bajuka

Value=>jzoo

Value=>zoo


<C>HashSet

  1. Hashset internally implements hashmap.
  2. Hashset honours all the properties specified by set means it does not allow duplicates.
  3. It stores elements randomly.
  4. If you want to insert your custom object in the hashset then you must override the equals and hashcode methods.

package com.collection;
import java.util.HashSet;

import java.util.Iterator;

import java.util.Set;

/**

*

*

*

*Rules: 1.Hashset can have null

* 2.HashSet can have only unique items.

* 3.Internally hashset implemented using hashmap and every item stored in

* HashSet is stored as key in HashMap and dummy Object is added as value in hashmap

* In this way hashset maintains uniquenes.

* HashSet does not maintain order

*

*/

public class HashSetExample {
public static void main(String[] args) {

Set<String> hashSetObj=new HashSet<String>();

hashSetObj.add(“Shiv”);hashSetObj.add(“Shiv”);

hashSetObj.add(null);hashSetObj.add(“jagjit”);

hashSetObj.add(“amar”);
Iterator<String> it=hashSetObj.iterator();

while(it.hasNext())

{

System.out.println(“”+it.next());

}
}
}

/*

* Output

null

amar

Shiv

jagjit

*/

Leave a Reply

Your email address will not be published. Required fields are marked *