private static boolean moreThanOnce(ArrayList<Integer> list, int number) {
if (list.contains(number)) {
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
如何list.contains检查是否在列表中多次找到该号码?我可以用for循环创建一个方法,但我想知道是否可以使用.contains. 感谢帮助!
您可以使用Stream:
private static boolean moreThanOnce(ArrayList<Integer> list, int number) {
return list.stream()
.filter(i -> i.equals (number))
.limit(2) // this guarantees that you would stop iterating over the
// elements of the Stream once you find more than one element
// equal to number
.count() > 1;
}
Run Code Online (Sandbox Code Playgroud)
你不能只用contains. 这只是测试该项目是否在列表中的任何位置。
不过,您可以使用indexOf。有两种重载indexOf,其中一种允许您在列表中设置一个位置以开始搜索。所以:找到一个之后,从那个位置之后的一个开始:
int pos = list.indexOf(number);
if (pos < 0) return false;
return list.indexOf(number, pos + 1) >= 0;
Run Code Online (Sandbox Code Playgroud)
或将最后一行替换为:
return list.lastIndexOf(number) != pos;
Run Code Online (Sandbox Code Playgroud)
如果您想要更简洁的方式(尽管在一次未找到的情况下,它会迭代整个列表两次):
return list.indexOf(number) != list.lastIndexOf(number);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
395 次 |
| 最近记录: |