List conversion between different data types
What would be the simplest way to convert List<Integer> to List<String>
objects. Currently I iterate through all the integers and add them to a List<String> objects
, is there a utility function which is already开发者_如何学运维 available?
You found a simple way. The type are "incompatible", so you need a conversion rule anyway (which is simple in your case). The algorithm will always be O(n), regardless of iterating through the collections manually or calling some API method from some 3rd party library (JRE doesn't offer API for your task).
While there are some libraries that can do general List
transformations (like Google's Guava) using one for this case probably won't save you any lines of code as you'd need to create a Function
object, and that alone involves so much boilerplate that your existing code is probably smaller.
I don't think we have a utility function for this task. Even there exist a utility function for this, it might have to iterate the List<Integer>
Do you have to have a List structure? Why not do a Map<Integer, String>
, and when an integer is inserted, a String value of that integer can be created.
I don't think there is an automatic way to do this, simply because of the way Java compiles Generic arguments (called type erasure, a complicated way of saying "Haha, we're actually saving only Object references and the compiler inserts casts to the generic argument every time you do a get()" ).
Why do you have to convert it to a list of Strings? Isn't it just the same to every time you need a list of strings to just iterate through the list of Integers and call toString() on each one?
EDIT:
either way, here's a solution that will work:
public static List<String> convToString(List<Integer> list){
List<String> ret = new ArrayList<String>();
for (Integer i : list){
ret.add(i.toString());
}
return ret;
}
And back again !
public static List<Integer> convToInteger(List<String> list){
List<Integer> ret = new ArrayList<Integer>();
for (String s : list){
ret.add(Integer.parseInt(s));
}
return ret;
}
精彩评论