English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce programme, vous apprendrez à vérifier si un array contient une valeur donnée en Java.
public class Contains { public static void main(String[] args) { int[] num = {1, 2, 3, 4, 5}; int toFind = 3; boolean found = false; for (int n : num) { if (n == toFind) { found = true; break; } } if(found) System.out.println(toFind + " Found"); else System.out.println(toFind + " Not found"); } }
When running the program, the output is:
3 Trouvé
Dans le programme ci-dessus, nous avons un tableau d'entiers stocké dans la variable num. De même, le nombre à trouver est stocké dans toFind
Maintenant, nous utilisons une boucle foreach pour parcourir tous les éléments de num et vérifier si toFind est égal à n
Si c'est le cas, nous mettons find à true et sortons de la boucle. Sinon, nous passons à l'itération suivante
import java.util.stream.IntStream; public class Contains { public static void main(String[] args) { int[] num = {1, 2, 3, 4, 5}; int toFind = 7; boolean found = IntStream.of(num).anyMatch(n -> n == toFind); if(found) System.out.println(toFind + " Found"); else System.out.println(toFind + " Not found"); } }
When running the program, the output is:
7 Introuvable
Dans le programme ci-dessus, nous n'avons pas utilisé une boucle foreach, mais avons converti l'array en IntStream et utilisé sa méthode anyMatch()
La méthode anyMatch() prend un prédicat, une expression ou une fonction renvoyant une valeur booléenne. Dans notre exemple, le prédicat compare chaque élément n du flux avec toFind et renvoie true ou false
Si l'un des éléments n renvoie true, found sera également mis à true
import java.util.Arrays; public class Contains { public static void main(String[] args) { String[] strings = {"One", "Two", "Three", "Four", "Five"}; String toFind = "Four"; boolean found = Arrays.stream(strings).anyMatch(t -> t.equals(toFind)); if(found) System.out.println(toFind + " Found"); else System.out.println(toFind + " Not found"); } }
When running the program, the output is:
Four found
In the above program, we used the non-primitive data type String and used the Arrays.stream() method to convert it to a stream first, and then used anyMatch() to check if the array contains the given value toFind