Ejemplo 1: comprobar si una matriz contiene un elemento java
import java.util.Arrays;
// For String
String[] array = {"Boto", "Nesto", "Lepta"};
String toSearch = "Nesto";
// Inline
if (Arrays.toString(array).contains(toSearch)) {
// Do something if it's found
}
// Multi line
String strArray = Array.toString(array);
if (strArray.contains(toSearch)) {
// Do your thing
}
// Different elements
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int number = 5;
String checker = Arrays.toString(numbers);
// The toString of int in some cases can happen without explicitly saying so
// In this example we convert both
if (checker.contains(Integer.toString(number)) {
// Found.
}
Ejemplo 2: java comprobar si el elemento existe en la matriz
package com.mkyong.core;
import java.util.Arrays;
import java.util.List;
public class StringArrayExample1 {
public static void main(String[] args) {
String[] alphabet = new String[]{"A", "B", "C"};
// Convert String Array to List
List<String> list = Arrays.asList(alphabet);
if(list.contains("A")){
System.out.println("Hello A");
}
}
}
Copy
Ejemplo 3: cómo encontrar contener elementos en una matriz 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 + " is found.");
else
System.out.println(toFind + " is not found.");
}
}
Ejemplo 4: java comprobar si el elemento existe en la matriz
// Convert to stream and test it
boolean result = Arrays.stream(alphabet).anyMatch("A"::equals);
if (result) {
System.out.println("Hello A");
}
Copy
Ejemplo 5: compruebe si la matriz contiene un número en java
public static boolean contains(final int[] arr, final int key) {
return Arrays.stream(arr).anyMatch(i -> i == key);
}
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)