Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List[Any] to List[Int]

Tags:

scala

How can I convert

List(1, 2, "3")

to

List(1, 2, 3)

since List(1, 2, "3") is of type List[Any] and I can't use .toInt on Any.

like image 616
Masupilami Avatar asked Mar 16 '14 20:03

Masupilami


People also ask

How do I turn a list into an int?

The most Pythonic way to convert a list of strings to a list of ints is to use the list comprehension [int(x) for x in strings] . It iterates over all elements in the list and converts each list element x to an integer value using the int(x) built-in function.

Can we convert list into integer in Python?

We can apply the map function to convert each element of the list into a string and then join each of them to form a final list. Applying the int function makes the final result an integer.

How do I convert a list of strings to a list of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList); Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList , as String extends Object .

How do you create an integer list in Python?

In Python, a list is created by placing elements inside square brackets [] , separated by commas. A list can have any number of items and they may be of different types (integer, float, string, etc.). A list can also have another list as an item.


2 Answers

That should be sufficient solution:

l.map(_.toString.toInt)
like image 84
liosedhel Avatar answered Sep 20 '22 15:09

liosedhel


Starting Scala 2.13 and the introduction of String#toIntOption, we can make @liosedhel's answer a bit safer if needs be:

// val l: List[Any] = List(1, 2, "3")
l.flatMap(_.toString.toIntOption)
// List[Int] = List(1, 2, 3)
like image 24
Xavier Guihot Avatar answered Sep 22 '22 15:09

Xavier Guihot