简体   繁体   中英

Using Java spliterator with Scala

I am querying a database in Scala that returns a java iterable object. I call the spilterator method to create a spilterator object but I have no idea to to use the tryAdvance or forEachRemaining in Scala syntax.

The Java syntax equivalent is below and it works:

Spliterator<String> splitStr = nameList.spliterator();
while(splitStr.tryAdvance((n) -> System.out.println("name - " + n)));

Here is what I have in Scala:

val nameListSplit = nameList.spliterator()
while (splitStr.tryAdvance((n) -> println("name - " + n))

As you can see I have no idea how to to call use the tryAdvance() method in scala, same goes for the forEachRemaining method.

The direct translation:

while(res4.tryAdvance { n => System.out.println("name - "+ n) }) ()
//                        ^ = not -                              ^^ unit (or {}); not ;
//                    ^ Braces instead of parens are purely style

The idiomatic translation:

nameList.forEach { n => println(s"name - $n") }
//       ^ foreach not iterator ^ interpolator not string +
//                      ^ println not System.out.println
//       ^ forEach in Java, foreach in Scala (pretty sure Scala had them first)
for(n <- nameList.asScala) println(s"name - $n")
// ^ for-comprehension (sugar for chained foreach, map, flatMap, filter, withFilter depending on context (generalized monad-comprehensions))
//    ^ <- as in "take n from nameList.asScala"
//                ^ convert to a Scala collection (import collection.JavaConverters._) (needed for foreach not forEach; someone should add AnyVal wrappers for that)
//                        ^ add yield here to do a (flat)map instead of foreach

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