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();
添加回答
舉報