How to loop over TreeSet inward Java amongst example

In our before articles, nosotros convey learned how to loop over ArrayList inwards Java together with yous tin role the same logic to loop over a TreeSet. You tin role both, enhanced for loop together with Iterator to traverse over TreeSet inwards Java. Though, worth noting is that Iterator returned yesteryear the iterator() method of TreeSet returns elements inwards the sorted lodge which is imposed yesteryear the Comparator yous convey provided to TreeSet at the fourth dimension of instantiation. By default, if yous don't render whatever custom Comparator than TreeSet sorts elements inwards their natural lodge e.g. String elements are sorted inwards alphabetic lodge together with Integer elements are sorted inwards numeric order. When yous iterate over a TreeSet the iterator follows this order.

You tin likewise role the enhanced for loop, which also internally uses the Iterator and traverse the TreeSet inwards the same order, but yous cannot take an chemical component there. On the other hand, Iterator allows yous to take elements piece iterating over TreeSet. In this article, yous volition discovery the examples of both approaches.


For those who are novel to TreeSet, H5N1 TreeSet is a sorted collection inwards Java. You insert an chemical component inwards whatever lodge but when yous iterate through the collection, the values are automatically presented inwards the sorted order. The sorting is accomplished yesteryear a tree information structure. The electrical flow implementation of java.util.TreeSet uses a Red-Black tree. For a detailed description of red-black trees, run into a practiced algorithm mass e.g. Introduction to Algorithms By Thomas Cormen, Charles Leiserson, Ronald Rivest together with Clifford Stein. Every fourth dimension an chemical component is added to a tree, it is placed into its proper sorting position. Therefore, the iterator e'er visits the elements inwards sorted order.

 enhanced for loop together with Iterator to traverse over  How to loop over TreeSet inwards Java alongside example



Iterating over TreeSet using Iterator

You tin follow iii steps to start iterating over TreeSet using Iterator, recall this is going from start to final chemical component inwards the sorted order.

1) acquire the Iterator yesteryear calling iterator() method
2) Use a for or piece loop alongside hasNext()
3) Call the next() method

Iterator<String> itr = treeSetOfScrips.iterator(); while (itr.hasNext()) {    System.out.println(itr.next()); }

You tin likewise take the electrical flow chemical component yesteryear calling the remove() method of Iterator, don't role the remove() method provided yesteryear the java.util.Collection interface because that volition effect inwards ConcurrentModificationException equally shown here.



Looping over TreeSet using enhanced for loop of Java 5
Here is the sample code to loop over TreeSet using advanced for loop, Remember yous cannot take elements when yous  are using enhanced for loop of JDK 1.5 release.

for (String stock : treeSetOfScrips) {    System.out.println(stock); }

There is likewise a 3rd means to iterate over TreeSet inwards Java but that is alone available from JDK 8 onwards. You tin role the forEach() method to iterate over whatever Collection including TreeSet inwards Java 8 because this method comes from java.util.Iterable interface.

Here is a squeamish slide of showing how to loop over TreeSet using both iterator together with enhanced for loop of JDK v inwards Java program:

 enhanced for loop together with Iterator to traverse over  How to loop over TreeSet inwards Java alongside example


Java Program to traverse over TreeSet inwards Java

Here is our consummate Java plan which shows measurement yesteryear measurement ask to iterate over TreeSet inwards Java. This plan contains both examples i.e. iterating over TreeSet using Iterator together with using enhanced for loop of Java 5.

import java.util.TreeSet; import java.util.Iterator; import java.util.Set;  public class TreeSetLoopingDemo{  public static void main(String args[]) {  // Creating together with initializing an TreeSet for iteration Set<String> treeSetOfScrips = new TreeSet<>(); treeSetOfScrips.add("MSFT"); treeSetOfScrips.add("INFY"); treeSetOfScrips.add("BABA"); treeSetOfScrips.add("GOOG"); treeSetOfScrips.add("AMZN");  System.out.println("TreeSet: " + treeSetOfScrips);  // Example 1 - iterating over TreeSet using Iterator // Obtaining the Iterator Iterator<String> itr = treeSetOfScrips.iterator();  // traversing over TreeSet System.out.println("Traversing over TreeSet using Iterator"); while (itr.hasNext()) { System.out.println(itr.next()); }  // Example two - looping over TreeSet using for loop System.out.println("Looping over TreeSet using advanced for loop"); for (String stock : treeSetOfScrips) { System.out.println(stock); } } }  Output: TreeSet: [AMZN, BABA, GOOG, INFY, MSFT] Traversing over TreeSet using Iterator AMZN BABA GOOG INFY MSFT Looping over TreeSet using advanced for loop AMZN BABA GOOG INFY MSFT

That's all almost how to iterate over TreeSet inwards Java. You tin role whatever of the approach to loop over a TreeSet but the recommendation is to role Iterator peculiarly if yous desire to take elements from TreeSet piece iterating over it. You tin role enhanced for loop for only accessing the elements e.g. for printing contents of TreeSet. This approach is similar to Iterator but results inwards cleaner code.

Further Learning
Java Fundamentals: Collections
From Collections to Streams inwards Java 8 Using Lambda Expressions
Java Programming Interview Exposed yesteryear Makham

If yous are curious to larn to a greater extent than almost TreeSet together with Java Collection framework yous tin likewise depository fiscal establishment tally out next articles:
  • Comprehensive ask to Java Collection framework (book)
  • 3 ways to loop over a Map inwards Java? (solution)
  • The departure betwixt TreeSet together with HashSet inwards Java? (answer)
  • How to traverse over a List inwards Java? (example)
  • 6 departure betwixt LinkedHashSet together with TreeSet inwards Java? (answer)
  • How to iterate over HashSet inwards Java? (solution)
  • The best means to iterate over each entry of HashMap inwards Java? (answer)
  • Core Java, Volume 1 ninth Edition yesteryear Cay S. Horstmann (read)

Subscribe to receive free email updates:

0 Response to "How to loop over TreeSet inward Java amongst example"

Posting Komentar