Skip to content
Related Articles

Related Articles

Improve Article

How to loop over TreeSet in Java

  • Last Updated : 10 Apr, 2020

Given a TreeSet in Java, the task is to loop over this TreeSet.

TreeSet provides an implementation of the SortedSet Interface and SortedSet extends Set Interface. It behaves like simple set with the exception that it stores elements in sorted format.

Following are the features of TreeSet.

  • TreeSet uses tree data structure for storage.
  • Objects are stored in sorted, ascending order. But we can iterate in descending order using method TreeSet.descendingIterator().
  • Access and retrieval times are very fast which make TreeSet an excellent choice for storage of large volume of data in sorted format.
  • TreeSet doesn’t use hashCode() and equals() methods to compare it’s elements. It uses compare() (or compareTo()) method to determine the equality of two elements.

Below are the two methods to loop over the TreeSet in Java:

  1. Using Iterator: Iterator can be created over the TreeSet objects. Hence this iterator can be used to traverse or loop through the TreeSet.

    Syntax:



    Iterator iterator = ts.iterator();
    while (iterator.hasNext())
        System.out.print(iterator.next());
    

    Program:




    // Java program to loop over TreeSet
      
    import java.util.Iterator;
    import java.util.TreeSet;
      
    public class TreeSetExample {
        public static void main(String[] args)
        {
            TreeSet<Integer>
                ts = new TreeSet<Integer>();
            ts.add(10);
            ts.add(61);
            ts.add(87);
            ts.add(39);
      
            // Create an Iterator over the TreeSet
            Iterator<Integer> iterator = ts.iterator();
      
            // Loop over the TreeSet values
            // and print the values
            System.out.print("TreeSet: ");
            while (iterator.hasNext())
                System.out.print(iterator.next()
                                 + ", ");
            System.out.println();
        }
    }
    Output:
    TreeSet: 10, 39, 61, 87,
    
  2. Using Enhanced For loop: Enhanced For loop can be used to loop over the TreeSet in the below manner.

    Syntax:

    for (Integer value : ts)
        System.out.print(value);
    }
    

    Program:




    // Java program to loop over TreeSet
      
    import java.util.Iterator;
    import java.util.TreeSet;
      
    public class TreeSetExample {
        public static void main(String[] args)
        {
            TreeSet<Integer>
                ts = new TreeSet<Integer>();
            ts.add(10);
            ts.add(61);
            ts.add(87);
            ts.add(39);
      
            // Loop over the TreeSet values
            // and print the values
            System.out.print("TreeSet: ");
            for (Integer value : ts)
                System.out.print(value
                                 + ", ");
            System.out.println();
        }
    }
    Output:
    TreeSet: 10, 39, 61, 87,
    
  3. Using Java 8 forEach / stream: Java 8 forEach / stream can be used to loop over the TreeSet in the below manner.

    Syntax:

    // Using forEach
    Tree_Set.forEach(iterator -> System.out.print(i + ” “));

    // Using stream
    Tree_Set.stream().map(iterator -> String.valueOf(i)).collect(Collectors.joining(“, “))

    Program:




    // Java program to loop over TreeSet
    // Needful libraries
    import java.util.Iterator;
    import java.util.TreeSet;
    import java.util.Arrays;
    import java.util.stream.Collectors;
      
    public class TreeSetExample {
        public static void main(String[] args)
        {
            // TreeSet object
            TreeSet<Integer>
                ts = new TreeSet<Integer>();
      
            // Adding elements to the TreeSet
            ts.addAll(Arrays.asList(10, 61, 87, 39));
      
            // Loop over the TreeSet & print values
            System.out.print("TreeSet without Comma: ");
      
            // Iterating through the TreeSet
            // using forEach
            ts.forEach(i -> System.out.print(i + " "));
            System.out.println();
      
            // Loop over the TreeSet & print values
            System.out.print("TreeSet with Comma: ");
      
            // Iterating through the TreeSet
            // using stream
            System.out.print(
                ts.stream().map(
                               i -> String.valueOf(i))
                    .collect(
                        Collectors.joining(", ")));
        }
    }
    Output:
    TreeSet without Comma: 10 39 61 87
    TreeSet with Comma: 10, 39, 61, 87
    

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :