用于检查数组(字符串或原始类型)是否包含特定值的Java示例,并使用Java 8流API更新了这些值。
1.字符串数组
1.1检查字符串数组是否包含某个值“ A”。
StringArrayExample1.java
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");
}
}
}
输出量
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检查字符串数组是否包含多个值的示例:
StringArrayExample2.java
package com.mkyong.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
List<String> list = 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对于像int[]
这样的原始数组,您需要对其进行循环并手动测试条件:
PrimitiveArrayExample1.java
package com.mkyong.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使用Java 8,编码要简单得多〜
ArrayExample1.java
package com.mkyong.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
注意
要检查原始数组是否包含多个值,请像上面的示例1.2一样,将该数组转换为List并进行比较。
参考文献
翻译自: https://mkyong.com/java/java-check-if-array-contains-a-certain-value/