Java,简化检查 int 数组是否包含 int [英] Java, Simplified check if int array contains int
本文介绍了Java,简化检查 int 数组是否包含 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上我的伙伴一直在说我可以通过使用不同的方式检查 int 数组是否包含 int 来缩短我的代码,尽管他不会告诉我它是什么:P.
Basically my mate has been saying that I could make my code shorter by using a different way of checking if an int array contains an int, although he won't tell me what it is :P.
当前:
public boolean contains(final int[] array, final int key) {
for (final int i : array) {
if (i == key) {
return true;
}
}
return false;
}
也试过这个,虽然由于某种原因总是返回false.
Have also tried this, although it always returns false for some reason.
public boolean contains(final int[] array, final int key) {
return Arrays.asList(array).contains(key);
}
有人可以帮我吗?
谢谢.
推荐答案
这里是 Java 8 解决方案
Here is Java 8 solution
public static boolean contains(final int[] arr, final int key) {
return Arrays.stream(arr).anyMatch(i -> i == key);
}
这篇关于Java,简化检查 int 数组是否包含 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文