如何使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
设置数据
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));
Run Code Online (Sandbox Code Playgroud)
如果您检查 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;
}
Run Code Online (Sandbox Code Playgroud)
在您的代码中将在类对象equals上调用Test。
作为解决方案,要么覆盖equals方法以 return true,如果id匹配。但我想说这不是一个好的解决方案,因为equals方法应该遵循一些合同。
因此,正确的选择应该是在这里使用StreamsAPI(尽管 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);
Run Code Online (Sandbox Code Playgroud)