How to convert list<String> into String in Dart without iteration?

38,918

Solution 1

join is a method of the List class, rather than String:

List<String> yourList = ["20", "3005", "2"];

// To test that the above the above
yourList.join() == '2030052';     // true
yourList.join(',') == '20,3005,2'; // true, with "," delimiter

Solution 2

This might not be the best solution, but you can reduce a collection to a single value by iteratively combining elements of the collection using the reduce method in Dart Lists.

String nums = numsList.reduce((value, element) => value + ',' + element);

You have to remember that, the iterable must have at least one element. If it has only one element, that element is returned.

Share:
38,918
Haikel
Author by

Haikel

💻Love Programming☀️.

Updated on July 09, 2022

Comments

  • Haikel
    Haikel almost 2 years

    Is there a method in Dart like the String.join() method in Java & c#?

    input:

    nums: ["20",  "3005",  "2"]
    

    output:

    nums = "2030052"
    
  • zerkms
    zerkms over 6 years
    yourList.join()?
  • Mohamed Dernoun
    Mohamed Dernoun about 4 years
    @zerkms yes this do the job and return a String
  • zerkms
    zerkms about 4 years
    @MohamedDernoun it was a comment to point out to the typo Mike made which they fixed.
  • Al Foиce    ѫ
    Al Foиce ѫ almost 3 years
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.