import java.util.*;
class TreeSetDemo
{
public static void main(String args[])
{
//create TreeSet
TreeSet<String> hs=new TreeSet<String>();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
//Iterator to display elements
System.out.println("Displaying contents of hs using for each: ");
Iterator itr=hs.iterator();
while(itr.hasNext())
{
Object element=itr.next();
System.out.print(element + "-");
}
System.out.println();
//For each, alternative to iterator
System.out.println("Displaying contents of hs using for each: ");
for(String s:hs)
System.out.print(s + " ");
System.out.println();
//--------------------------------------------------------
//adding a to z in TreeSet
System.out.println();
LinkedHashSet<Character> h=new LinkedHashSet<Character>();
for(int i=97;i<122;i++)
h.add((char)i);
h.add('b');
System.out.println(h);
//Iterator to display elements
System.out.println("Displaying contents of hs using for each: ");
Iterator itr1=h.iterator();
while(itr1.hasNext())
{
Object element=itr1.next();
System.out.print(element + "-");
}
System.out.println();
//For each, alternative to iterator
System.out.println("Displaying contents of h using for each: ");
for(Character s1:h)
System.out.print(s1 + " ");
System.out.println();
}
}
Output:
[A, B, C, D, E, F]
Displaying contents of hs using Iterator:
A-B-C-D-E-F-
Displaying contents of hs using for each:
A B C D E F
[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y]
Displaying contents of h using Iterator:
a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-
Displaying contents of h using for each:
a b c d e f g h i j k l m n o p q r s t u v w x y
Note:
- LinkedHashSet guarantee the elements in sorted, ascending order.
- In LinkedHashSet ListIterator cannot be used.
- LinkedHashSet implements NavigableSet interface.
No comments:
Post a Comment