简体   繁体   中英

Storing Individual Data Using a ForEach Loop Scala

I'm brand new to Scala and am trying to figure out how to iterate over an array of Buckets (from Amazon AWS), and take data from each bucket and store it in a new array.

In Java this would just be

ArrayList<String> names = new ArrayList<String>(); 

for(Bucket bucket : bucket) {
    names.add(bucket.getName();
}

But, how do I do this in Scala? I know that I define a function of some kind such that it would be something like

buckets.foreach(bucket => FILL IN SOME WAY OF FILLING UP ARRAY)

But, that's all I got.

Any and all help would be greatly appreciated. Thanks,

This is equivalent in scala, if buckets is a scala collection.

val names = buckets map (_.getName)

If it's not you need to say

import scala.collection.JavaConverters._
buckets.asScala.map(_.getName)

For more structural approach, that is discouraged in scala and you should not do this, but for sake of completenes so you can see what you would have to do to get your solution to work, you could use foreach like so

var names = Vector.empty[String]
buckets foreach (bucket => names :+= bucket.getName)

or with foreach loop, that might be more familiar

var names = Vector.empty[String]
for (bucket <- buckets) {
    names :+= bucket.getName
}

However you can still use for comprehension and achieve a valid result in a functional way

val names = for (bucket <- buckets) yield bucket.getName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM