Java 8 – Iterable.forEach, Iterator.remove methods tutorial with examples
Collections API is the most popular and widely used utility API in the Java universe. With the advent of Functional Interfaces, Lambdas and Streams in Java 8, Collections API has also undergone changes to accomodate and build-upon the newly introduced functional programming features. The most widely used Collection classes and interfaces such as Iterable and Iterator, Collection, List and Map have all been enhanced in JDK 1.8 with new features and methods.
This is the 1 st article in a 4 part article series in which I will cover the changes introduced in Java 8 Collections in detail.
In this part 1 of 4, I will be covering the new default method named forEach() introduced in java.lang.Iterable interface with examples. This will be followed by understanding the new default implementation of Iterator interface’s remove() method, and how it makes implementing the Iterator easier than before.
New default method forEach() added to the Iterable Interface in Java 8
Iterable interface is a commonly extended interface among the Collections interfaces as it provides the ability to iterate over the members of a collection. Collection , List and Set are among the important Collections interfaces that extend Iterable , apart from other interfaces.
Java 8’s new Iterable.forEach() method has the following signature –
Iterable.forEach() method ‘consumes’ all the elements of the iterable collection of elements passed to it. The logic for consumption is passed to the method as an instance of a Consumer functional interface. An important point to note is that the forEach method iterates internally over the collection of elements passed to it rather than externally. You can read about declarative internal iterators and how they differ from commonly used external iterators in this tutorial here Click to read detailed tutorial explaining internal vs external iterators .
Let us now take a look at Java code showing how to use Iterable.forEach() method for consuming the elements of an Iterable collection –
package com.javabrahman.java8.collections; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class IterableForEachExample < public static void main(String args[])< ListintList= Arrays.asList(12,25,9); System.out.println("List elements printed using Iterable.forEach"); intList.forEach(System.out::println); Set intSet=new HashSet<>(); intSet.add(50); intSet.add(1); System.out.println("Set elements printed using Iterable.forEach"); intSet.forEach(System.out::println); > >
List elements printed using Iterable.forEach
12
25
9
Set elements printed using Iterable.forEach
1
50
- A List of primitive int s, named intList , is created using the Arrays.asList() method.
- forEach() method is invoked on the List instance – intList . As we read above, List inherits the forEach() method’s default implementation from Iterable interface.
- We pass a method reference Click to read tutorial on Java 8 Method References to System.out.println() method, which is a Consumer type of function, as parameter to the forEach() method.
- forEach() method internally iterates and consumes, or prints, the elements of intList .
- Next we created an instance of a Set , named intSet , by using its concrete implementation HashSet .
- Set also inherits Iterable . Hence, we are able to print the elements in intSet using the forEach() method similar to the way we did with intList .
New default method remove() added to Iterator interface in Java 8
Prior to Java 8, implementing Iterator interface without the support for remove() method implied that the designers had to override the method and throw an UnsupportedOperationException . Such an override was commonly done and over the years had become kind of staple in Iterator implementations not supporting the remove operation.
With Java 8 arrived the feature of adding default implementations of methods in interfaces itself. Java designers have used this new feature and added a default implementation of the remove() method in the Iterator interface itself which throws UnsupportedOperationException .
As a result, the practice of overriding the remove() method, whenever it wasn’t supported, has now been inverted to overriding the remove() method only when remove functionality has to be implemented. This has removed the unnecessary overhead of overriding and throwing the UnsuportedOperationException everytime when implementing an Iterator without remove functionality.
The default implementation of remove() method in Java 8’s Iterable is as shown below –
As you can see in the above code, the default implementation of Iterator.remove() method just throws an UnsupportedOperationException with message «remove» .
Conclusion
In this tutorial we dipped our feet into the waters of Java 8 Collection Enhancements by taking a look at the changes in Iterable and Iterator interfaces.
In the forthcoming parts I will be taking you to the depths of Java 8 Collections enhancements, where I will explain the changes in important Collection classes viz. Collection , List and Map interfaces. Specifically, among the Map enhancements we will take a look at the new methods added in Java 8 which make multi-value maps handling easier than before.
Руководство Java Iterator
Следуйте за нами на нашей фан-странице, чтобы получать уведомления каждый раз, когда появляются новые статьи.
Facebook
1- Iterator
Iterator — это один из способов обхода (traverse) элементов Collection. Ниже приведены характеристики Iterator:
- Iterator не гарантирует порядок итераций элементов.
- Iteratorможет разрешить удаление элементов из Collection во время итерации, что зависит от типа Collection.
Причина, по которой вы можете перемещаться (traverse) по элементам of Collection с помощью Iterator, заключается в том, что Collection расширяется из интерфейса Iterable.
// Definition of the Collection interface: public interface Collection extends Iterable // Definition of the Iterable interface: public interface Iterable < Iteratoriterator(); default void forEach(Consumer action) < Objects.requireNonNull(action); for (T t : this) < action.accept(t); >> default Spliterator spliterator() < return Spliterators.spliteratorUnknownSize(iterator(), 0); >>
boolean hasNext() E next(); // Optional operation. default void remove() default void forEachRemaining(Consumer action)
2- Examples
С помощью объекта Collection можно создать Iterator методом Collection.iterator(), а затем обходить элементы of Iterator с помощью метода next().
package org.o7planning.iterator.ex; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class IteratorEx1 < public static void main(String[] args) < // List is a subinterface of Collection. Listflowers = new ArrayList(); flowers.add("Tulip"); flowers.add("Daffodil"); flowers.add("Poppy"); flowers.add("Sunflower"); flowers.add("Bluebell"); Iterator iterator = flowers.iterator(); while(iterator.hasNext()) < String flower = iterator.next(); System.out.println(flower); >> >
Tulip Daffodil Poppy Sunflower Bluebell
3- remove()
При обходе элементов of Collection с помощью Iterator, вы можете удалить текущий элемент из Collection. Метод Iterator.remove() позволяет это сделать. Однако не все Iterator поддерживают эту операцию, это зависит от типа Collection. Если он не поддерживается, будет выдано исключение UnsupportedOperationException.
// Optional Operation public default void remove()
package org.o7planning.iterator.ex; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Iterator_remove_ex1 < public static void main(String[] args) < // List is a subinterface of Collection. Listyears = new ArrayList(); years.add(1998); years.add(1995); years.add(2000); years.add(2006); years.add(2021); Iterator iterator = years.iterator(); while(iterator.hasNext()) < Integer current = iterator.next(); if(current % 2 ==0) < iterator.remove(); // Remove current element. >> // After remove all even numbers: for(Integer year: years) < System.out.println(year); >> >
Пример о Collection, Iterator которой не поддерживает операцию Iterator.remove():
package org.o7planning.iterator.ex; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class Iterator_remove_ex2 < public static void main(String[] args) < // Fixed-size List. // Its Iterator does not support remove() operation. Listyears = Arrays.asList(1998, 1995, 2000, 2006, 2021); Iterator iterator = years.iterator(); while(iterator.hasNext()) < Integer current = iterator.next(); if(current % 2 ==0) < iterator.remove(); // UnsupportedOperationException!! >> // After remove all even numbers: for(Integer year: years) < System.out.println(year); >> >
Exception in thread "main" java.lang.UnsupportedOperationException: remove at java.base/java.util.Iterator.remove(Iterator.java:102) at org.o7planning.iterator.ex.Iterator_remove_ex2.main(Iterator_remove_ex2.java:20)
4- forEachRemaining(Consumer)
Выполняем данное действие для каждого оставшегося элемента до тех пор, пока все элементы не будут обработаны или действие не вызовет исключение.
public default void forEachRemaining(Consumer action)
package org.o7planning.iterator.ex; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class Iterator_forEachRemaining < public static void main(String[] args) < // Set is a subinterface of Collection. Setflowers = new HashSet(); flowers.add("Tulip"); flowers.add("Daffodil"); flowers.add("Poppy"); flowers.add("Sunflower"); flowers.add("Bluebell"); // Note: Iterator doesn't guarantee iteration order Iterator iterator = flowers.iterator(); String flower1 = iterator.next(); String flower2 = iterator.next(); System.out.println("Flower 1: " + flower1); System.out.println("Flower 2: " + flower2); System.out.println(); iterator.forEachRemaining(flower -> System.out.println(flower)); > >
Flower 1: Poppy Flower 2: Tulip Daffodil Sunflower Bluebell
5- ListIterator
ListIterator — это подинтерфейс of Iterator. Это один из способов обхода элементов List. В отличие от Iterator, ListIterator поддерживает перемещение элементов как в прямом, так и в обратном направлениях. ListIterator также поддерживает удаление, обновление или вставку элемента во время итерации.
View more Tutorials:
Это онлайн курс вне вебсайта o7planning, который мы представляем, он включает бесплатные курсы или курсы со скидкой.
Complete E-Commerce Course — Java,Spring,Hibernate and MySQL
Design Patterns in C# and .NET
Android and iOS Apps for Your WordPress Blog
Build Apps with ReactJS: The Complete Course
Selenium WebDriver + Java для начинающих
Byte-Sized-Chunks: Dynamic Prototypes in Javascript
JavaFX : Learn to build powerful client applications
JSP, Servlets and JDBC for Beginners: Build a Database App
2D Game Development With HTML5 Canvas, JS — Tic Tac Toe Game
AWS Administration – Database, Networking, and Beyond
Supreme NodeJS Course — For Beginners
Learning Oracle Application Express ( Oracle Apex ) Training
AngularJS Fundamentals and Practice
Hibernate in Practice — The Complete Course
Dart and Flutter: The Complete Developer’s Guide
Learn Spring Boot — Rapid Spring Application Development
Backup and Restore Fundamentals in PostgreSQL DB — Level 2
Ultimate Ionic 3 — Build iOS and Android Apps with Angular 4
Learn SSRS SQL Reporting & Business Intelligence Essentials
Happy Flutter — Sport News Apps Flutter
Learn Spring Boot in 100 Steps — Beginner to Expert
MySQL 101 for beginners
Mastering Bootstrap 4
* * Crash Course Into JavaFX: The Best Way to make GUI Apps
Understanding JDBC with PostgreSQL (A step by step guide)
Java Language Iterator and Iterable Removing elements using an iterator
The Iterator.remove() method is an optional method that removes the element returned by the previous call to Iterator.next() . For example, the following code populates a list of strings and then removes all of the empty strings.
List names = new ArrayList<>(); names.add("name 1"); names.add("name 2"); names.add(""); names.add("name 3"); names.add(""); System.out.println("Old Size : " + names.size()); Iterator it = names.iterator(); while (it.hasNext()) < String el = it.next(); if (el.equals("")) < it.remove(); >> System.out.println("New Size : " + names.size());
Note that is the code above is the safe way to remove elements while iterating a typical collection. If instead, you attempt to do remove elements from a collection like this:
a typical collection (such as ArrayList ) which provides iterators with fail fast iterator semantics will throw a ConcurrentModificationException .
The remove() method can only called (once) following a next() call. If it is called before calling next() or if it is called twice following a next() call, then the remove() call will throw an IllegalStateException .
The remove operation is described as an optional operation; i.e. not all iterators will allow it. Examples where it is not supported include iterators for immutable collections, read-only views of collections, or fixed sized collections. If remove() is called when the iterator does not support removal, it will throw an UnsupportedOperationException .
PDF — Download Java Language for free