【发布时间】:2016-06-16 09:35:18
【问题描述】:
这可能是一个幼稚的问题。我有一个案例类“书”,定义如下:
case class Book(title : String, authors : List[String])
在我的 main 方法中,我定义了几个 Book 记录如下:
val books = List(
Book(title = "Book1", authors = List("Author1", "Author2")),
Book(title = "Book2", authors = List("Author3", "Author4")),
Book(title = "Book3", authors = List("Author2", "Author5")),
Book(title = "Book4", authors = List("Author6", "Author3")),
Book(title = "Book5", authors = List("Author7", "Author8")),
Book(title = "Book6", authors = List("Author5", "Author9"))
)
我正在编写一个查询来检索撰写过不止一本书的作者姓名,我的查询如下:
val authorsWithMoreThanTwoBooks =
(for {
b1 <- books
b2 <- books
if b1.title != b2.title
a1 <- b1.authors
a2 <- b2.authors
if a1 == a2
} yield a1)
println(authorsWithMoreThanTwoBooks)
这会打印出List(Author2, Author3, Author2, Author5, Author3, Author5)(作者的名字出现了两次,这是意料之中的,因为每对书都会被使用两次,例如 (b1,b2) 和 (b2,b1))。
当然我可以使用distinct 来解决这个问题,但另一种方法是不在列表中创建记录,而是在集合中创建记录:
val books = Set(
Book(title = "Book1", authors = List("Author1", "Author2")),
Book(title = "Book2", authors = List("Author3", "Author4")),
Book(title = "Book3", authors = List("Author2", "Author5")),
Book(title = "Book4", authors = List("Author6", "Author3")),
Book(title = "Book5", authors = List("Author7", "Author8")),
Book(title = "Book6", authors = List("Author5", "Author9"))
)
for 表达式和println 之后的输出:Set(Author5, Author2, Author3)
为什么会发生这种行为?为什么Set 上的for 表达式会生成另一个Set 而不是List?如果需要,是否可以获得具有重复值的相关作者的List?
【问题讨论】:
-
集合如何包含重复项?
-
他们不能,这就是我的意思。我错过了什么吗?
-
我的问题是,为什么我们从“书籍”的后一个定义的 for 表达式中得到一个集合,而不是一个列表。相应地更新了我的问题。
-
你解决了吗?如果您觉得我没有真正回答您的问题,请随时解释您仍然困惑的问题。
-
我确实设法解决了它,忘记了问题,感谢您的帮助。
标签: scala collections scala-collections