Tutorials Hut

Java Collection: LinkedHashSet and TreeSet

In this article we will look into Java LinkedHashSet and TreeSet.

LinkedHashSet

LinkedHashSet class is similar to HashSet but data is ordered in linkedhashset while the same is not true for hashset. Linkedhashset maintains the order in which data was inserted but in hashset no such ordering is guaranteed. Linkedhashset extends hashset class which extends AbstractSet andAbstractSet implements Set interface.

LinkedHashSet Creation and Constructor

1. LinkedHashSet(): This constructor is default constructor

Syntax:

LinkedHashSet hs = new LinkedHashSet();

2. LinkedHashSet(Collection C): Initializes with another collection.

Syntax

LinkedHashSet hs = new LinkedHashSet(Collection c);

3. LinkedHashSet(int size): Initializes with a capacity.

Syntax

LinkedHashSet hs = new LinkedHashSet(int size);

4. LinkedHashSet(int capacity, float fillRatio)

LinkedHashSet hs = new LinkedHashSet(int capacity, int fillRatio);

Example of LinkedHashSet with add, addAll, remove and iterator

import java.util.Iterator;
import java.util.LinkedHashSet;

public class SetExam<code>ples {
public static void main(String[] args) {
LinkedHashSet linkedHashSet = new LinkedHashSet();
//add
linkedHashSet.add("Rom");</code>

LinkedHashSet linkedHashSet2 = new LinkedHashSet();
linkedHashSet2.add("Dolly");
//add all
linkedHashSet.addAll(linkedHashSet2);

linkedHashSet.add("Jonny");
System.out.println("linkedHashSet: "+linkedHashSet);

//Remove
linkedHashSet.remove("Jonny");

//Iterator
Iterator itr = linkedHashSet.iterator();
while(itr.hasNext()) {
System.out.println("After removing jonny: " + itr.next());
}
}
}

Output

linkedHashSet: [Rom, Dolly, Jonny]
After removing jonny: Rom
After removing jonny: Dolly

TreeSet

TreeSet class is similar to HashSet, but elements of TreeSet are ordered in ascending order.

TreeSet extends hashset class which extends AbstractSet andAbstractSet impliments Set interface.

Example of TreeSet with add, addAll, remove, and Iterator

import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.TreeSet;

public class SetExamples {
public static void main(String[] args) {
    TreeSet linkedHashSet = new TreeSet();
    //add
    linkedHashSet.add("Rom");
    LinkedHashSet linkedHashSet2 = new LinkedHashSet();
   linkedHashSet2.add("Dolly");

    //add all
    linkedHashSet.addAll(linkedHashSet2);
    linkedHashSet.add("Jonny");
  System.out.println("linkedHashSet: "+linkedHashSet);

    //Remove
     linkedHashSet.remove("Jonny");

    //Iterator
    Iterator itr = linkedHashSet.iterator();
    while(itr.hasNext()) {
        System.out.println("After removing jonny: " + itr.next());
    }
}
}

Output

linkedHashSet: [Dolly, Jonny, Rom]
After removing jonny: Dolly
After removing jonny: Rom

Next Article

  • Queue and PriorityQueue

 


















  • Leave a Reply

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