3 回答

TA贡献1852条经验 获得超1个赞
基本上,要了解为什么编译器不会出错,您应该查看String.equals()方法实现
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
现在,让我们回到这一行:
s.getId().equals(map.entrySet().stream().map(Map.Entry::getKey))
我们知道s.getId()is 的 typeString和map.entrySet().stream().map(Map.Entry::getKey)is 的 type Stream<String>。
由于Stream<String>is notinstanceof String,很明显每次与String.equals()方法比较时都会返回(因此,最后计数为0 )。并且编译器不会发出错误,因为实际上没有发生任何非法事件(考虑到 的实现)。falses.getId()map.entrySet().stream().map(Map.Entry::getKey)String.equals()
count此外,可能,在没有警告的情况下找到最干净的方法是:
System.out.println(
stulist.stream()
.map(Student::getId)
.filter(map::containsKey)
.count());

TA贡献1831条经验 获得超4个赞
首先,您可能想要的可能是:
System.out.println(stulist.stream()
.filter(s -> map.keySet().contains(s.getId()))
.count());
其次,equals在您的代码中使用的比较是不正确的,因为它在两种不同类型的对象之间String和Stream<String>。
// here the 's.getId' is a String while 'map.entrySet()...map()' provides 'Stream<String>'
.filter(s -> s.getId().equals(map.entrySet().stream().map(Map.Entry::getKey)))

TA贡献1735条经验 获得超5个赞
您可以使用map.containsKey
避免在每个学生条目的条目集上运行流:
long count = stulist.stream().map(student::getId).filter(map::containsKey).count();
您收到警告是因为检测到您正在测试String.equals(Stream<String>)
,这当然很可能是一个错误(在您的示例中,它肯定是)。
如果您要使用当前的逻辑,则正确的检查必须是:
long count = stulist.stream() .filter(s -> map.entrySet() .stream() .map(Map.Entry::getKey) .anyMatch(s.getId()::equals)) .count();
添加回答
举报