logo

Comment parcourir une liste en Java

En Java, Liste c'est une interface du Cadre de collecte . Il nous permet de maintenir la collection ordonnée d’objets. Les classes d'implémentation de l'interface List sont ArrayList, LinkedList, Pile , et Vecteur . ArrayList et LinkedList sont largement utilisés dans Java . Dans cette section, nous apprendrons comment parcourir une liste en Java . Tout au long de cette section, nous utiliserons Liste des tableaux .

Java pour la boucle

  1. Boucle for de base
  2. Boucle for améliorée

Itérateurs Java

  1. Itérateur
  2. ListItérateur

Méthode Java pour chaque

  1. Itérable.forEach()
  2. Stream.forEach()

Java pour la boucle

Boucle for de base

Java pour la boucle est la boucle de contrôle de flux la plus courante pour l’itération. La boucle for contient une variable qui fait office de numéro d'index. Il s'exécute jusqu'à ce que toute la liste ne soit pas itérée.

Syntaxe:

ah, java
 for(initialization; condition; increment or decrement) { //body of the loop } 

ItérerListeExample1.java

 import java.util.*; public class IterateListExample1 { public static void main(String args[]) { //defining a List List city = Arrays.asList(&apos;Boston&apos;, &apos;San Diego&apos;, &apos;Las Vegas&apos;, &apos;Houston&apos;, &apos;Miami&apos;, &apos;Austin&apos;); //iterate list using for loop for (int i = 0; i <city.size(); i++) { prints the elements of list system.out.println(city.get(i)); } < pre> <p> <strong>Output</strong> </p> <pre> Boston San Diego Las Vegas Houston Miami Austin </pre> <h3>Enhanced for Loop</h3> <p>It is similar to the basic for loop. It is compact, easy, and readable. It is widely used to perform traversal over the List. It is easy in comparison to basic for loop.</p> <p> <strong>Syntax:</strong> </p> <pre> for(data_type variable : array | collection) { //body of the loop } </pre> <p> <strong>IterateListExample2.java</strong> </p> <pre> import java.util.*; public class IterateListExample2 { public static void main(String args[]) { //defining a List List city = Arrays.asList(&apos;Boston&apos;, &apos;San Diego&apos;, &apos;Las Vegas&apos;, &apos;Houston&apos;, &apos;Miami&apos;, &apos;Austin&apos;); //iteration over List using enhanced for loop for (String cities : city) { //prints the elements of the List System.out.println(cities); } } } </pre> <p> <strong>Output</strong> </p> <pre> Boston San Diego Las Vegas Houston Miami Austin </pre> <h2>Java Iterator</h2> <h3>Iterator</h3> <p> <a href="/iterator-java">Java provides an interface Iterator</a> to <strong>iterate</strong> over the Collections, such as List, Map, etc. It contains two key methods next() and hasNaxt() that allows us to perform an iteration over the List.</p> <p> <strong>next():</strong> The next() method perform the iteration in forward order. It returns the next element in the List. It throws <strong>NoSuchElementException</strong> if the iteration does not contain the next element in the List. This method may be called repeatedly to iterate through the list, or intermixed with calls to previous() to go back and forth.</p> <p> <strong>Syntax:</strong> </p> <pre> E next() </pre> <p> <strong>hasNext():</strong> The hasNext() method helps us to find the last element of the List. It checks if the List has the next element or not. If the hasNext() method gets the element during traversing in the forward direction, returns true, else returns false and terminate the execution.</p> <p> <strong>Syntax:</strong> </p> <pre> boolean hasNext() </pre> <p> <strong>IterateListExample3.java</strong> </p> <pre> import java.util.*; public class IterateListExample3 { public static void main(String args[]) { //defining a List List city = Arrays.asList(&apos;Boston&apos;, &apos;San Diego&apos;, &apos;Las Vegas&apos;, &apos;Houston&apos;, &apos;Miami&apos;, &apos;Austin&apos;); //iterate List using enhances for loop Iterator cityIterator = city.iterator(); //iterator over List using while loop while(cityIterator.hasNext()) { System.out.println(cityIterator.next()); } } } </pre> <p> <strong>Output</strong> </p> <pre> Boston San Diego Las Vegas Houston Miami Austin </pre> <h3>ListIterator</h3> <p>The ListIterator is also an interface that belongs to java.util package. It extends <strong>Iterator</strong> interface. It allows us to iterate over the List either in forward or backward order. The forward iteration over the List provides the same mechanism, as used by the Iterator. We use the next() and hasNext() method of the Iterator interface to iterate over the List.</p> <p> <strong>IterateListExample4.java</strong> </p> <pre> import java.util.*; public class IterateListExample4 { public static void main(String args[]) { //defining a List List city = Arrays.asList(&apos;Boston&apos;, &apos;San Diego&apos;, &apos;Las Vegas&apos;, &apos;Houston&apos;, &apos;Miami&apos;, &apos;Austin&apos;); //iterate List using the ListIterator ListIterator listIterator = city.listIterator(); while(listIterator.hasNext()) { //prints the elements of the List System.out.println(listIterator.next()); } } } </pre> <p> <strong>Output</strong> </p> <pre> Boston San Diego Las Vegas Houston Miami Austin </pre> <h2>Java forEach Method</h2> <h3>Iterable.forEach()</h3> <p>The Iterable interface provides forEach() method to iterate over the List. It is available since Java 8. It performs the specified action for each element until all elements have been processed or the action throws an exception. It also accepts Lambda expressions as a parameter.</p> <p> <strong>Syntax:</strong> </p> <pre> default void forEach(Consumer action) </pre> <p>The default implementation behaves like:</p> <pre> for (T t : this) action.accept(t); </pre> <p>It accepts <strong>action</strong> as a parameter that is <strong>non-interfering</strong> (means that the data source is not modified at all during the execution of the stream pipeline) action to perform on the elements. It throws <strong>NullPointerException</strong> if the specified action is null.</p> <p>The <strong>Consumer</strong> is a functional interface that can be used as the assignment target for a lambda expression or method reference. T is the type of input to the operation. It represents an operation that accepts a single input argument and returns no result.</p> <p> <strong>IterateListExample5.java</strong> </p> <pre> import java.util.*; public class IterateListExample5 { public static void main(String args[]) { //defining a List List city = Arrays.asList(&apos;Boston&apos;, &apos;San Diego&apos;, &apos;Las Vegas&apos;, &apos;Houston&apos;, &apos;Miami&apos;, &apos;Austin&apos;); //iterate List using forEach city.forEach(System.out::println); } } </pre> <p> <strong>Output</strong> </p> <pre> Boston San Diego Las Vegas Houston Miami Austin </pre> <h3>Stream.forEach()</h3> <p>Java Stream interface allows us to convert the List values into a stream. With the help of Stream interface we can access operations like forEach(), map(), and filter().</p> <p> <strong>Syntax:</strong> </p> <pre> void forEach(Consumer action) </pre> <p>It accepts <strong>action</strong> as a parameter that is <strong>non-interfering</strong> (means that the data source is not modified at all during the execution of the stream pipeline) action to perform on the elements.</p> <p>The <strong>Consumer</strong> is a functional interface that can be used as the assignment target for a lambda expression or method reference. T is the type of input to the operation. It represents an operation that accepts a single input argument and returns no result.</p> <p> <strong>IterateListExample5.java</strong> </p> <pre> import java.util.*; public class IterateListExample5 { public static void main(String args[]) { //defining a List List city = Arrays.asList(&apos;Boston&apos;, &apos;San Diego&apos;, &apos;Las Vegas&apos;, &apos;Houston&apos;, &apos;Miami&apos;, &apos;Austin&apos;); //iterate List using forEach loop city.stream().forEach((c) -&gt; System.out.println(c)); } } </pre> <p> <strong>Output</strong> </p> <pre> Boston San Diego Las Vegas Houston Miami Austin </pre> <hr></city.size();>

Boucle for améliorée

C’est similaire à la boucle for de base. Il est compact, simple et lisible. Il est largement utilisé pour effectuer un parcours sur la liste. C’est facile par rapport à la boucle for de base.

Syntaxe:

 for(data_type variable : array | collection) { //body of the loop } 

ItérerListeExample2.java

 import java.util.*; public class IterateListExample2 { public static void main(String args[]) { //defining a List List city = Arrays.asList(&apos;Boston&apos;, &apos;San Diego&apos;, &apos;Las Vegas&apos;, &apos;Houston&apos;, &apos;Miami&apos;, &apos;Austin&apos;); //iteration over List using enhanced for loop for (String cities : city) { //prints the elements of the List System.out.println(cities); } } } 

Sortir

 Boston San Diego Las Vegas Houston Miami Austin 

Itérateur Java

Itérateur

Java fournit un itérateur d'interface à répéter sur les collections, telles que List, Map, etc. Il contient deux méthodes clés next() et hasNaxt() qui nous permettent d'effectuer une itération sur la liste.

suivant(): La méthode next() effectue l’itération dans l’ordre direct. Il renvoie l'élément suivant de la liste. Ça jette NoSuchElementException si l'itération ne contient pas l'élément suivant dans la liste. Cette méthode peut être appelée à plusieurs reprises pour parcourir la liste, ou mélangée à des appels à previous() pour aller et venir.

Syntaxe:

Language de machine
 E next() 

hasNext() : La méthode hasNext() nous aide à trouver le dernier élément de la List. Il vérifie si la liste contient l'élément suivant ou non. Si la méthode hasNext() récupère l'élément lors du parcours dans le sens avant, renvoie vrai, sinon renvoie faux et termine l'exécution.

Syntaxe:

 boolean hasNext() 

ItérerListeExample3.java

 import java.util.*; public class IterateListExample3 { public static void main(String args[]) { //defining a List List city = Arrays.asList(&apos;Boston&apos;, &apos;San Diego&apos;, &apos;Las Vegas&apos;, &apos;Houston&apos;, &apos;Miami&apos;, &apos;Austin&apos;); //iterate List using enhances for loop Iterator cityIterator = city.iterator(); //iterator over List using while loop while(cityIterator.hasNext()) { System.out.println(cityIterator.next()); } } } 

Sortir

 Boston San Diego Las Vegas Houston Miami Austin 

ListItérateur

Le ListIterator est également une interface qui appartient au package java.util. Il s'étend Itérateur interface. Cela nous permet de parcourir la liste dans l'ordre avant ou arrière. L'itération avant sur la liste fournit le même mécanisme que celui utilisé par l'itérateur. Nous utilisons les méthodes next() et hasNext() de l’interface Iterator pour parcourir la liste.

ItérerListeExample4.java

 import java.util.*; public class IterateListExample4 { public static void main(String args[]) { //defining a List List city = Arrays.asList(&apos;Boston&apos;, &apos;San Diego&apos;, &apos;Las Vegas&apos;, &apos;Houston&apos;, &apos;Miami&apos;, &apos;Austin&apos;); //iterate List using the ListIterator ListIterator listIterator = city.listIterator(); while(listIterator.hasNext()) { //prints the elements of the List System.out.println(listIterator.next()); } } } 

Sortir

conception unique
 Boston San Diego Las Vegas Houston Miami Austin 

Méthode Java pour chaque

Itérable.forEach()

L'interface Iterable fournit la méthode forEach() pour parcourir la liste. Il est disponible depuis Java 8. Il effectue l'action spécifiée pour chaque élément jusqu'à ce que tous les éléments aient été traités ou que l'action lève une exception. Il accepte également les expressions Lambda comme paramètre.

Syntaxe:

 default void forEach(Consumer action) 

L'implémentation par défaut se comporte comme :

 for (T t : this) action.accept(t); 

Il accepte action comme paramètre qui est non-interférant (signifie que la source de données n'est pas du tout modifiée lors de l'exécution du pipeline de flux) action à effectuer sur les éléments. Ça jette NullPointerException si l'action spécifiée est nulle.

Le Consommateur est une interface fonctionnelle qui peut être utilisée comme cible d'affectation pour une expression lambda ou une référence de méthode. T est le type d'entrée dans l'opération. Il représente une opération qui accepte un seul argument d'entrée et ne renvoie aucun résultat.

ItérerListeExample5.java

 import java.util.*; public class IterateListExample5 { public static void main(String args[]) { //defining a List List city = Arrays.asList(&apos;Boston&apos;, &apos;San Diego&apos;, &apos;Las Vegas&apos;, &apos;Houston&apos;, &apos;Miami&apos;, &apos;Austin&apos;); //iterate List using forEach city.forEach(System.out::println); } } 

Sortir

classe abstraite en Java
 Boston San Diego Las Vegas Houston Miami Austin 

Stream.forEach()

L'interface Java Stream nous permet de convertir les valeurs de la liste en un flux. Avec l'aide de l'interface Stream, nous pouvons accéder à des opérations telles que forEach(), map() et filter().

Syntaxe:

 void forEach(Consumer action) 

Il accepte action comme paramètre qui est non-interférant (signifie que la source de données n'est pas du tout modifiée lors de l'exécution du pipeline de flux) action à effectuer sur les éléments.

Le Consommateur est une interface fonctionnelle qui peut être utilisée comme cible d'affectation pour une expression lambda ou une référence de méthode. T est le type d'entrée dans l'opération. Il représente une opération qui accepte un seul argument d'entrée et ne renvoie aucun résultat.

ItérerListeExample5.java

 import java.util.*; public class IterateListExample5 { public static void main(String args[]) { //defining a List List city = Arrays.asList(&apos;Boston&apos;, &apos;San Diego&apos;, &apos;Las Vegas&apos;, &apos;Houston&apos;, &apos;Miami&apos;, &apos;Austin&apos;); //iterate List using forEach loop city.stream().forEach((c) -&gt; System.out.println(c)); } } 

Sortir

 Boston San Diego Las Vegas Houston Miami Austin