java - 如何将包含方法与自定义数组列表一起使用?
问题描述
如何使用contains方法仅按 id 搜索,我想在不使用循环的情况下检查 id 是否等于 4,如何?
测试班
public class Test {
private int id;
private String name;
private int age;
public Test(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
设置数据
List <Test> list = new ArrayList <> ();
list.add(new Test(1, "Name 1", 25));
list.add(new Test(2, "Name 2", 37));
list.add(new Test(3, "Name 3", 63));
list.add(new Test(4, "Name 4", 19));
list.add(new Test(5, "Name 5", 56));
解决方案
如果您检查 java 库中的 contains 方法。它在内部调用indexOf
方法(内部调用方法),它通过对对象indexOfRange
进行方法调用来返回索引。equals
int indexOfRange(Object o, int start, int end) {
Object[] es = elementData;
if (o == null) {
for (int i = start; i < end; i++) {
if (es[i] == null) {
return i;
}
}
} else {
for (int i = start; i < end; i++) {
if (o.equals(es[i])) {
return i;
}
}
}
return -1;
}
在您的代码equals
中将在Test
类对象上调用。
作为解决方案,如果匹配,则覆盖equals
要返回的方法。但我会说这不是一个好的解决方案,因为方法应该遵循一些合同。true
id
equals
因此,在这里也应该使用Streams
API 是正确的(尽管 Stream 也将在内部使用迭代)。
List <Test> list = new ArrayList <> ();
list.add(new Test(1, "Name 1", 25));
list.add(new Test(2, "Name 2", 37));
list.add(new Test(3, "Name 3", 63));
list.add(new Test(4, "Name 4", 19));
list.add(new Test(5, "Name 5", 56));
boolean isMatch = arr.stream().anyMatch(i-> i.id == toMatch);
推荐阅读
- python-3.x - 从 pyspark 数据框中的列返回字母数字值
- linux - 使用来自主机的 CA Trust Bundle 构建 Docker
- loops - 原生 Google 表格中的嵌套“for”循环(无脚本)
- java - Java 8 Lambda 映射
到地图 > - angular - 在角度上动态更改 LOCALE_ID
- rust - 为什么解构借用的枚举需要取消引用其字段?
- oauth-2.0 - 我在哪里可以在门户中获取我的 Azure AD B2C 颁发者 URL
- javascript - 当输入在页面加载或用户更改时具有值时更新 Alpinejs x-data
- r - 当 rmarkdown 符合时,R 包可用选项卡会显示
- javascript - React、useEffect 清理不适用于 removeEventListener、useRef、视差效果