2

I'm writing a method in java which requires ArrayList<String> as its output. In this method, String concatenation is frequently used. I use StringBuilder instead of String since String is more expensive in concatenation.

Before returning result, how could I cast all elements in ArrayList<StringBuilder> to ArrayList<String>?

2
  • 1
    Do you mean: how can I cast all elements in ArrayList<StringBuilder> to String? You can't cast them. Commented Sep 26, 2014 at 1:53
  • I reopened the question because How do you cast a List of objects from one type to another in Java? concerns casting a list of supertypes to a list of subtypes, whereas StringBuilder and String are unrelated. @SotiriosDelimanolis you could add your Stream#map answer now. Commented Sep 26, 2014 at 2:14

1 Answer 1

7

how could I cast all elements in ArrayList<StringBuilder> to ArrayList<String>?

You can't and you shouldn't. Make it an ArrayList of one or the other.

Or if you must translate, then you'll need a for loop to iterate through the collection, building the new collection.

or I suppose you could declare the variable as an ArrayList<? extends CharSequence> -- nope that wouldn't work as we're nixed since we can't add(...) anything into a covariant structure, so we wouldn't be able to add anything to this list, just read from it.

Sign up to request clarification or add additional context in comments.

5 Comments

Use the new Stream#map(Function) functionality!
@SotiriosDelimanolis: I'm not familiar with that -- please make an answer with that information so we all can learn!
@HovercraftFullOfEels Sotirios meant something like List<String> listOfString = listOfStringBuffers.stream().map(builder->builder.toString()).collect(Collectors.toList()). BTW lambda expression builder->builder.toString() can be also written as StringBuilder::toString.
@Pshemo: Thanks! I've been putting off learning Lambdas and Java 8 for too long.
I was afk. That is what I meant. Your answer is plenty. This is just an implementation of what you described.

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.