how to convert a String sentence to arraylist in Kotlin

comma-separated string to arraylist kotlin
convert hashset to arraylist kotlin
kotlin array to arraylist
string to arraylist in java 8
convert list to arraylist kotlin
stringify arraylist kotlin
string to char array in kotlin
convert jsonarray to arraylist kotlin

I have this function to convert string sentence to list words. I created this function in Java and converted to Kotlin using default Kotlin conversion in Android Studio, but I believe there can be many ways to shorten this code in Awesome Kotlin. I will be good if you can share your piece of code and help me(and all) to improve our knowledge in Kotlin.

private fun stringToWords(mnemonic: String): List<String> {
    val words = ArrayList<String>()
    for (word in mnemonic.trim { it <= ' ' }.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) {
        if (word.isNotEmpty()) {
            words.add(word)
        }
    }
    return words
}

I would go for the following:

fun stringToWords(s : String) = s.trim().splitToSequence(' ')
    .filter { it.isNotEmpty() } // or: .filter { it.isNotBlank() }
    .toList()

Note that you probably want to adjust that filter, e.g. to filter out blank entries too... I put that variant in the comment... (if you use that one, you do not require an initial trim() though)

If you rather want to work with the Sequence you can do so by just omitting the .toList() at the end.

And as also Abdul-Aziz-Niazi said: same is also possible via extension function, if you require it more often:

fun String.toWords() = trim().splitToSequence(' ').filter { it.isNotEmpty() }.toList()

Kotlin – Convert comma-separated String to List & List to String , – To convert comma-separated String to List: use CharSequence. split() to split string into List. then call map() and pass transform function like trim or something to refine each item of the List. Kotlin Program to Convert List (ArrayList) to Array and Vice-Versa In this program, you'll learn to convert a list to an array using toArray() and array to list using asList() in Kotlin.

You can do it like this.. Just make a function of return type list.

 val s = "This is a sample sentence."

 val words:Array<String>  = s.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    for (i in words.indices) {
        // You may want to check for a non-word character before blindly
        // performing a replacement
        // It may also be necessary to adjust the character class
        words[i] = words[i].replace("[^\\w]".toRegex(), "")
    }

May this will help you :-)

Java - String to ArrayList conversion, In this java tutorial we are converting a String to an ArrayList. The steps for conversion are as follows: 1) First split the string using String split() I have an ArrayList of String in kotlin. private val list = ArrayList<String>() I want to convert it into String with a separator ",". I know we can do it programatically through loop but in other languages we have mapping functions available like in java we have. StringUtils.join(list); And in Swift we have

It's easier than you think:

fun stringToWords(mnemonic: String) = mnemonic.replace("\\s+".toRegex(), " ").trim().split(" ")

Remove multiple spaces, trim start and the end, split. Like an extention:

fun String.toWords() = replace("\\s+".toRegex(), " ").trim().split(" ")

After Roland's suggestion:

fun String.toWords() = trim().split("\\s+".toRegex())

Kotlin String Splitting – Stone Soup Programming, How do you convert a comma separated string to a list? Obviously, this isn’t ideal as we have to convert between the two types. It would be much nicer to be able to create and initialize an ArrayList directly. Fortunately, we can! Initializing an ArrayList with arrayListOf. As it turns out, the collections library includes a function for building an ArrayList in Kotlin directly:

You don't need scopes, the redundant "".toRegex() and the last expression. You can do something like this:

private fun stringToWords(mnemonic: String): List<String> {
    val words = ArrayList<String>()
    for (w in mnemonic.trim(' ').split(" ")) {
        if (w.isNotEmpty()) {
            words.add(w)
        }
    }
    return words
}

Additionally, If you use this method a lot in this project, you can make it an extension in string class. Paste this method in a separate file(outside a classes or add it in classless .kt file) so it has a global access. and then you can use it with any string like myString.toWords() anywhere in the project The method will look like this

inline fun String.toWords(): List<String> {
    val words = ArrayList<String>()
    for (w in this.trim(' ').split(" ")) {
        if (w.isNotEmpty()) {
            words.add(w)
        }
    }
    return words
}

A simple use of joinToString() Kotlin function to get comma , List<String> listOfStringColumn = new ArrayList(); using joinToString() to convert the list of Kotlin data classes into a comma separated string. However if you really need ArrayList you can create it too: val list = arrayListOf(*intArrayOf(5, 3, 0, 2).toTypedArray()) or using more idiomatic Kotlin API as suggested by @Ilya: val arrayList = intArrayOf(1, 2, 5).toCollection(ArrayList()) Or if you'd like to do the above yourself and save some allocations:

Collections Overview, In other words, you add a String to a list of String s the same way as you would modify the same mutable collection object, so the reference doesn't change. In Kotlin, the default implementation of List is ArrayList which you can think of as a  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more How to convert ArrayList to JSONArray() in Kotlin

Kotlin Program to Convert List (ArrayList) to Array and Vice-Versa, Example 1: Convert array list to array. fun main(args: Array<String>) { // an arraylist of vowels val vowels_list: List<String> = listOf("a", "e", "i", "o", "u") // converting  We use String's toCharArray() method to convert the string to an array of characters stored in chars. We then, use Arrays 's toString() method to print the elements of chars in an array like form. Here's the equivalent Java code: Java program to convert char to string and vice-versa

Convert a String to a List of Characters in Java, convertStringToCharList(String str). {. // Create an empty List of character. List<​Character> chars = new ArrayList<>();. // For each character in the String. ArrayList class is used to create a dynamic array in Kotlin. Dynamic array states that we can increase or decrease the size of an array as per requisites. It also provide read and write functionalities. ArrayList may contain duplicates and is non-synchronized in nature.

Comments