How to append semi-colon on to each element in an ArrayList<String> [duplicate]

做~自己de王妃 提交于 2019-12-31 04:57:06

问题


I am currently trying to append a semi-colon onto the end of each element in an ArrayList .

The code:

ArrayList<String> emailAddresses = new ArrayList<String>();

public void getEmailAddresses() throws InterruptedException {
    driver.findElement(By.className("userlink-0")).click();
    String emailAddress = driver.findElement(By.id("email")).getText();
    emailAddresses.add(emailAddress);
    hs.addAll(emailAddresses);
    emailAddresses.clear();
    emailAddresses.addAll(hs);

}

Eventually I will be taking this list of email addresses and outputting it to the recipients field for sending an email using Java. Hence why I am trying to append semi-colons to the elements in order to separate the email addresses.

Thanks


回答1:


Assuming that you use Java 8, you could do that using the Stream API with joining(CharSequence delimiter) as collector allowing to concatenate the input elements, separated by the specified delimiter, in encounter order as next:

String emails = emailAddresses.stream().collect(Collectors.joining(";"));



回答2:


As a primitive solution you may use:

for (int i = 0; i < emailAddresses.size(); i++) {
    emailAddresses.set(i, emailAddresses.get(i).concat(";"));
}



回答3:


Removing commas with semi-colons doesn't sounds to me a full proof solution that will grantee to not break in future. Since that requires doing syso on list and then use regex to replace commas and brackets. Instead I'll use StringBuilder, iterate over the list and append semi-colons.

StringBuilder str = new StringBuilder();
for(int i=0; i< emailAddresses.size(); i++ )
{
    str.append(emailAddresses.get(i));
    //to skip last emailAddress 
    if(i+1 == emailAddresses.size())
        continue;
    str.append(";");
}
System.out.println(str.toString());



回答4:


You can add semicolon to each element while adding them to ArrayList. But suppose you want to do some processing later on, so now you have to take care of that extra semicoln you have added.

So a better solution could be, just add all element as they are and just print below line on the recipient filed where you want them:

System.out.println(emailAddresses .toString().replace("[", "").replace("]", "").replace(",", ";"));

If any problem ask in comment section.



来源:https://stackoverflow.com/questions/41059194/how-to-append-semi-colon-on-to-each-element-in-an-arrayliststring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!