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
Try this
String[] str = {"url1","url2","url3","url4"};
ArrayList<String> strList = new ArrayList<String>();
for (String k:str)
strList.add("'" +k+ "'");
System.out.println("Printing the list");
for(String k:strList)
System.out.println(k);
Iterate the list (for/while).
For each element in the list append <element-of-list>
. Hint: use append()
on StringBuilder
.
Truncate/substring the list to remove the last element added. Hint: use substring on String
class.
for list you can convert this by Java 8
list.stream().collect(Collectors.joining("','", "'", "'"));
If you have your elements in an array, you can do something like this:
import java.util.ArrayList;
class Test1{
public static void main(String[] args) {
String[] s = {"url1","url2","url3","url4"};
ArrayList<String> sl = new ArrayList<String>();
for (int i = 0; i < s.length; i++) {
sl.add("'" + s[i] + "'");
}
}
}
import org.apache.commons.lang.StringUtils;
...
...
String arr[] = new String[4];
arr[0] = "my";
arr[1] = "name";
arr[2] = "is";
arr[3] = "baybora";
String join = "'" + StringUtils.join(arr,"','") + "'";
Result:
'my','name','is','baybora'
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<String> 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());
}
}