Looping set in java

Iterate through a Collection in Java

This Java Collections tutorial demonstrates the different techniques to iterate over a Java Collection (List, Set and Map) using for-loop, enhanced for-loop, Iterator and Java 8 Stream.

The following examples show how to iterate over the items of a List in Java.

With recent coding trends, using streams allow us to iterate the list items, perform operations on items, and collect the results in a seamless manner.

List list = List.of("A", "B", "C", "D"); list.stream() //other operation as needed .forEach(System.out::println);

Recently introduced in java 8, this method can be called on any Iterable and takes one argument implementing the functional interface java.util.function.Consumer .

List list = List.of("A", "B", "C", "D"); list.forEach(System.out::println);

The enhanced for loop is also an excellent way to iterate over a List, and it produces readable code.

List list = List.of("A", "B", "C", "D"); for(String s : list)

The Iterator returned from the List.iterator() method provides hasNext() and next() methods that can help traverse the list items in a sequential manner.

List list = List.of("A", "B", "C", "D"); Iterator itr = list.iterator(); while(itr.hasNext())

Last but the least, a traditional for-loop can also be used to traverse the list items.

List list = List.of("A", "B", "C", "D"); for( int i=0; i

Set is very similar to List types except:

  • Set does not allow duplicate elements
  • Set does not provide get() method to fetch an item using the index.

So we can reuse the iteration methods of List with Set also. Only traditional for-loop cannot be used due to the unavailability of indexes-based access.

Set set = Set.of("A", "B", "C", "D"); //Stream set.stream() //other operation as needed .forEach(System.out::println); //Iterable.forEach() set.forEach(System.out::println); //Enhanced for-loop for(String s : set) < System.out.println(s); >//Iterator Iterator itr1 = set.iterator(); while(itr1.hasNext())

The Map stores the key-value pairs. The keys are unique and each value is associated with a single key. We can iterate over the keys and values, both, in the Map.

The Map.keySet() method returns the Set of keys in the map so we can use the methods applicable for Set for iterating over the keys in the Map.

Map map = Map.of("A", 1, "B", 2, "C", 3); //Stream map.keySet().stream().forEach(System.out::println); //Iterable.forEach() map.keySet().forEach(System.out::println); //Iterator Iterator keysItr = map.keySet().iterator(); while(keysItr.hasNext())

The Map.values() method returns the List of values in the map so we can use the methods applicable to the List for iterating over the keys in the Map.

Map map = Map.of("A", 1, "B", 2, "C", 3); //Stream map.values().stream().forEach(System.out::println); //Iterable.forEach() map.values().forEach(System.out::println); //Iterator Iterator valuesItr = map.values().iterator(); while (valuesItr.hasNext())

The Map.entrySet() method returns the Set of Map.Entry instances from the map so we can use the methods applicable to the Set for iterating over the entries in the Map.

Map map = Map.of("A", 1, "B", 2, "C", 3); //Stream map.entrySet().stream().forEach(System.out::println); //Iterable.forEach() map.entrySet().forEach(System.out::println); //Iterator Iterator  entryIterator = map.entrySet().iterator(); while (entryIterator.hasNext())

Источник

3 ways to loop over Set or HashSet in Java? Examples

Since Set interface or HashSet class doesn’t provide a get() method to retrieve elements, the only way to take out elements from a Set is to iterate over it by using the Iterator, or loop over Set using advanced for loop of Java 5. You can get the iterator by calling the iterator() method of the Set interface. This method returns an iterator over the elements in the sets but they are returned in no particular order, as Set doesn’t guarantee any order. Though individual Set implementations e.g. LinkedHashSet or TreeSet can impose ordering and in such iterator will return elements on that order.

You can only traverse in one direction using iterator i.e. from first to last elements, there is no backward traversing allowed as was the case with List interface and ListIterator . Similarly, if you use advanced for loop, then also you can traverse in only one direction.

In this tutorial, you will learn both ways to traverse over Set or HashSet in Java i.e. by using both Iterator and enhanced for loop. Btw, Java 8 also introduced a new to loop over a set, that is by using the forEach() method if you are lucky to be running on Java 8 then you can use that as well.

And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.

Iterating over Set using Iterator

  1. Obtain the iterator by calling the iterator() method.
  2. You can use while or for loop along with hasNext() , which returns true if there are more elements in the Set.
  3. Call the next() method to obtain the next elements from Set.
IteratorString> itr = setOfStocks.iterator(); // traversing over HashSet System.out.println("Traversing over Set using Iterator"); while(itr.hasNext())< System.out.println(itr.next()); >

Loop over HashSet using for loop

There are no particular steps to loop over Set using enhanced for loop, as you just need to use the Set as per loop construct as shown below:

for(String stock : setOfStocks)< System.out.println(stock); >

This will print all the stocks from the setOfStocks into the console.

Traversing over HashSet using forEach() method

This method is only available from Java 8 onwards. This forEach() method belongs to Iterable interface and since Set implements that you can use this to traverse over Set as shown below:

public class HashSetLooperJava8< public static void main(String args[]) < // Creating and initializing an HashSet for iteration SetString> setOfBooks = new HashSet<>(); setOfBooks.add("Effective Java"); setOfBooks.add("Clean Code"); setOfBooks.add("Refactoring"); setOfBooks.add("Head First Java"); setOfBooks.add("Clean Coder"); // iterating over HashSet using forEach() method in Java 8 setOfBooks.forEach(System.out::println); > > Output: Clean Code Effective Java Head First Java Clean Coder Refactoring

There is another forEach() method defined in the Stream class from the new JDK 8 Stream API, See 10 ways to use forEach in Java 8 for more examples.

Here is the summary of all three ways to iterate over HashSet or any Set in Java:

3 example to iterate over HashSet in Java

Java Program to loop over HashSet in Java

Here is a sample program to show you how you can loop over a Set in Java using both Iterator and advanced for loop. The only difference in the two ways is that you can remove elements while iterating using Iterator’s remove() method but you cannot remove elements while looping over HashSet using enhanced for loop, even though Set provides a remove() method. Doing so will result in ConcurrentModificationException in Java.

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

That’s all about how to traverse over HashSet or Set in Java. You can use the same technique to loop over other Set implementations like LinkedHashSet, TreeSet, EnumSet, CopyOnWriteHashSet or ConcurrentSkipListSet in Java.

All these implementations provide the iterator() method which returns the elements in the order this class individually guarantees like LinkedHashSet guarantees insertion order and TreeSet guarantees the sorted order imposed by Comparable or Comparator provided while creating TreeSet instance.

You can choose between Iterator and advanced for loop to traverse over Set depending upon whether you want to remove the elements during iterator or not. The iterator allows you to remove elements but enhanced for loop doesn’t allow that.

Источник

Читайте также:  Java class data field
Оцените статью