Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Scala: Convert List[B[A]] Into List[A]

DZone's Guide to

Scala: Convert List[B[A]] Into List[A]

Scala users know how powerful the language is for manipulating collections, but let's see in which order it's best to apply those manipulations.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

Hey, Scala squad! In this post, I’m going to show some ways of extracting values from a list or sequence of boxed elements. It’s a pretty common case when you have a Seq[B[A]], but instead of that, you need to get Seq[A].

To be more precise, it may be Seq[Try[String]] or List[Option[Int]].

It’s not a big secret that Scala has a lot of powerful functions for collection manipulation. But in what order should you apply them to achieve your desired result? I prepared multiple examples of how this may be solved. If you have better ideas, just put them in the comments.

In order to show how to flatten a list of Try or Option or whatever box type, we need to introduce some sequence.

val listOfTries: Seq[Try[String]] = Seq(
    Success("Yes"), 
    Success("Ok"),
    Failure(new Exception("No")), 
    Success("Deal"))


So the first method to extract Strings from listOfTries is to filter all of the elements by applying the isSuccess method and then mapping each of the success elements to its internal string value.

val listOfStrings = listOfTries.filter(_.isSuccess).map(_.get)


That's all right, but there may be an even more concise solution:

val listOfStrings = listOfTries.collect { 
    case Success(str) => str 
}


Since collect accepts PartialFunction, we just iterate through all of the elements, match them to Success, and finally retrieve their values.

Summary

The same approach may be used for processing sequences with Option elements. But I’m still curious about your thoughts regarding the solutions I illustrated above. You are more than welcome to comment on this short article

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java ,scala ,list ,collection ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}