scala 从集合中获取元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24571444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:23:27  来源:igfitidea点击:

Get element from Set

scala

提问by blue-sky

How can I get element at position in Set ?

如何在 Set 中的位置获取元素?

For a List can do :

对于列表可以做:

  val s : Set[(String, String)] = Set( ("a","b") )
  val l1 = l(0)

But for Set :

但是对于 Set :

  val s : Set[(String, String)] = Set( ("a","b") )
  val t1 = s(1)

I get compile time error :

我得到编译时错误:

Multiple markers at this line - type mismatch; found : Int(1) required: (String, String) - type mismatch; found : 
 Int(1) required: (String, String)

Update :

更新 :

converting to List is an option but I though should be able to access a element at position in Set

转换为 List 是一个选项,但我虽然应该能够访问 Set 中某个位置的元素

回答by senia

Setis not an ordered collection - you can't get element by index.

Set不是有序集合 - 您无法按索引获取元素。

You could use headmethod to get single element from Set(it's not the first element, just some element).

您可以使用head方法从中获取单个元素Set(它不是第一个元素,只是某个元素)。

You could also process all elements using foreachmethod:

您还可以使用foreach方法处理所有元素:

for (s <- Set("a", "b")) println(s)

If you want to get all elements in some order you should convert Setto Sequsing toSeqmethod like this:

如果你想以某种顺序获取所有元素,你应该转换SetSeq使用这样的toSeq方法:

val mySeq = mySet.toSeq