How to add or insert ' (single quotes) for every string in a list in which strings are separated by commas using Java

前端 未结 10 1236
夕颜
夕颜 2021-02-05 06:12

I have a list as below

[url1,url2,url3,url4] 

This list will be based on multiple selection from drop down list of HTML. So list size i.e., lis

10条回答
  •  孤独总比滥情好
    2021-02-05 07:01

    Also you can use Java8 built-in features for String concatenation and third-party libraries for wrapping each string in quotes.

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.runners.MockitoJUnitRunner;
    import org.springframework.util.StringUtils;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.StringJoiner;
    
    @RunWith(MockitoJUnitRunner.class)
    public class StringJoinerTest {
        @Test
        public void testStringJoiner() {
    
            //init test data
            String s1 = "team1";
            String s2 = "team2";
            List teams = new ArrayList<>(2);
            teams.add(s1);
            teams.add(s2);
    
            //configure StringJoiner
            //when some values will be added to joiner it will return string started with prefix "(" an finished with suffix ")"
            //between prefix and suffix values will be separated with delimiter ", "
            StringJoiner teamNames = new StringJoiner(", ", "(", ")");
            //if nothing has been added to the joiner it will return  this value ('')
            teamNames.setEmptyValue("(\'\')");
    
            //fill joiner with data
            for (String currentString : teams) {
                //if you need to wrap each string in single quotes you can do this via org.apache.commons.lang3.StringUtils#wrap
                // or org.springframework.util.StringUtils#quote
                teamNames.add(StringUtils.quote(currentString));
            }
    
            System.out.println(teamNames.toString());
        }
    }
    

提交回复
热议问题