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
.
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.
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.
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 .
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.
That should be sufficient solution:
l.map(_.toString.toInt)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With