1

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?

5
  • 8
    The code I wrote here works -- Seems like you could use a CodeReview codereview.stackexchange.com/tour Commented Jan 22, 2017 at 19:43
  • 1
    Why is your input a List of strings and not just a single string? What exactly are the elements of this list? Commented Jan 22, 2017 at 19:44
  • 3
    Is your input ["[Cat", "Dog", "Snake]"] (size 3) or ["[Cat, Dog, Snake]"] (size 1)? My guess is the latter, but ... why? Commented Jan 22, 2017 at 19:49
  • 2
    Hint: A "list of strings" doesn't need to be toString()-d. You already have a list, so iterate over it, trim() the values, Commented Jan 22, 2017 at 19:49
  • Please check out minimal reproducible example (guidance on providing code in the post) and provide input data for code in the post. As @cricket_007 commented toString call on list is very confusing - so hard to say why it is there and if removal will actually make code easier for data you have. Commented Jan 22, 2017 at 23:29

1 Answer 1

2

How about simply streaming and collecting to a list?

return list.stream().map(String::trim).collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.