Java –配列に特定の値が含まれているかどうかを確認しますか?
配列(文字列またはプリミティブ型)に特定の値が含まれているかどうかを確認するJavaの例。Java8ストリームAPIで更新されています。
1. 文字列配列
1.1 Check if a String Array contains a certain value “A”.
StringArrayExample1.java
package com.example.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 Listlist = Arrays.asList(alphabet); if(list.contains("A")){ System.out.println("Hello A"); } } }
出力
Hello A
Java 8では、これを行うことができます。
// Convert to stream and test it boolean result = Arrays.stream(alphabet).anyMatch("A"::equals); if (result) { System.out.println("Hello A"); }
1.2 Example to check if a String Array contains multiple values :
StringArrayExample2.java
package com.example.core; import java.util.Arrays; import java.util.List; public class StringArrayExample2 { public static void main(String[] args) { String[] alphabet = new String[]{"A", "C"}; // Convert String Array to List Listlist = Arrays.asList(alphabet); // A or B if (list.contains("A") || list.contains("B")) { System.out.println("Hello A or B"); } // A and B if (list.containsAll(Arrays.asList("A", "B"))) { System.out.println("Hello A and B"); } // A and C if (list.containsAll(Arrays.asList("A", "C"))) { System.out.println("Hello A and C"); } } }
出力
Hello A or B Hello A and C
2. プリミティブ配列
2.1 For primitive array like int[]
, you need to loop it and test the condition manually :
PrimitiveArrayExample1.java
package com.example.core; import java.util.Arrays; import java.util.List; public class PrimitiveArrayExample1 { public static void main(String[] args) { int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; if(contains(number, 2)){ System.out.println("Hello 2"); } } public static boolean contains(final int[] array, final int v) { boolean result = false; for(int i : array){ if(i == v){ result = true; break; } } return result; } }
出力
Hello 2
2.2 With Java 8, coding is much simpler ~
ArrayExample1.java
package com.example.core; import java.util.stream.IntStream; import java.util.stream.LongStream; public class TestDate { public static void main(String[] args) { int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; //Java 8 boolean result = IntStream.of(number).anyMatch(x -> x == 4); if (result) { System.out.println("Hello 4"); } else { System.out.println("Where is number 4?"); } long[] lNumber = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; boolean result2 = LongStream.of(lNumber).anyMatch(x -> x == 10); if (result2) { System.out.println("Hello 10"); } else { System.out.println("Where is number 10?"); } } }
出力
Hello 4 Hello 10
Note
プリミティブ配列に複数の値が含まれているかどうかを確認するには、the array
into a Listを変換し、上記の例1.2のように比較します。