简体   繁体   中英

Efficient use of trim and split for strings in Java

The code I wrote here works, but I am pretty sure it is awful and not so efficient. This function takes in input a list of strings which is splitted on comma and then each generated string is trimmed.

One example:

INPUT:    [[Cat, Dog, Snake]]
OUTPUT:   Cat Dog Snake

private List<String> splitListOfString(LinkedList<String> list)
{
    String mylist = list.toString();
    mylist = mylist.substring(2);
    mylist = mylist.substring(0, mylist.length() - 2);
    List<String> thelist = Arrays.asList(mylist.split(","));
    List<String> thelist2 = new LinkedList<String>();
    for (String string : thelist) {
        thelist2.add(string.trim());
    }
        return thelist2;
}

How would you improve this code?

简单地streamcollect到列表怎么样?

return list.stream().map(String::trim).collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM