我有两组对象,我想得到两组的交集。集合中的对象如下所示
@BeanInfo
class User {
@JsonProperty
@BeanProperty
var name:String = ""
@JsonProperty
@BeanProperty
var id:Long = 0
override def toString = name
override def equals(other: Any)= other match {
case other:User => other.id == this.id
case _ => false
}
}
在另一堂课中,我得到了用户集并希望看到交集。
val myFriends = friendService.getFriends("me")
val friendsFriends = friendService.getFriends("otheruser")
println(myFriends & friendsFriends)
上面的代码不起作用并打印
Set()
但是,如果我使用 foreach 手动遍历集合,我会得到想要的结果
var matchedFriends:scala.collection.mutable.Set[User] = new HashSet[User]()
myFriends.foreach(myFriend => {
friendsFriends.foreach(myFriend => {
if(myFriend == myFriend){
matchedFriends.add(myFriend)
}
})
})
println(matchedFriends)
上面的代码打印
Set(Matt, Cass, Joe, Erin)
这工作得很好
val set1 = Set(1, 2, 3, 4)
val set2 = Set(4,5,6,7,1)
println(set1 & set2)
以上印刷品
Set(1, 4)
集合操作 & &- 等是否仅适用于原始对象?我是否必须对我的用户对象做一些额外的事情才能使它起作用?