Convert list of strings into single string value; exclude all null list members

  • I have five string which contains some value I need to check if any of them contains value if yes then store them in Another string.

    Currently I'm doing this like below:

    List<string> slist = new List<string>();
    String s1 = 'abc';
    slist.add(s1);
    string s2 = 'bcd';
    slist.add(s2);
    string s3 = 'cde';
    slist.add(s3);
    string s4 = 'def';
    slist.add(s4);
    string s5 = 'efg';
    slist.add(s4);
    
    string allstirng;
    boolean check;
    for(String s: slist){
        if(!check){
            allstirng +=',';
        }
        allstirng += s;
        check = false;
    }
    

    Is there any other better way of doing this.

    Aren't you missing the logic for your 'check' boolean? something like: `String.isNotBlank(s)`. Besides, according to your question, you add your evaluated string to another one only if the first contains a value, but your code stores all the strings regardless of the value they have.

  • Eric

    Eric Correct answer

    6 years ago

    I am a little confused as there are no nulls but, not to mention just create the all string directly (unless you are trying to understand the concept :

    List<string> slist = new string[]{'abc','bcd','cde','def','efg'};
    
    slist.remove(null);
    string allstring = string.join(sList,',');
    

    Is a simplified version of your code

    You type faster than me. I was going to post (almost) the same code :D.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used