Converting a list between different data types

What will be the easiest way to convert List<Integer> to List<String> objects. I am currently repeating all integers and adding them to List<String> objects , is there already a useful function?

+4
source share
5 answers

You have found an easy way. The type is "incompatible", so you need a conversion rule (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 third-party library (the JRE does not offer an API for your task).

+5
source

Although there are some libraries that can perform general List conversions (e.g. Google Guava ) using one for this case, probably t will save you any lines of code, since you need to create a Function object, and this in itself includes many templates that your existing code is probably smaller.

+2
source

I don’t think there is an automatic way to do this, simply because of how Java compiles common arguments (called type erasure, a difficult way to say β€œHaha, we actually only save object references and the compiler inserts the cast into the general argument each time you do get () ").

Why should you convert it to a list of strings? Isn't it the same when you need a list of strings to just iterate over a list of integers and call toString () on each of them?


EDIT:

anyway, here is 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 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; } 
+1
source

I do not think we have a utility function for this task. Even for this, there is a utility function, you may need to iterate through List<Integer>

+1
source

Do I need to have a list structure? Why not make Map<Integer, String> , and when an integer is inserted, the String value of that integer can be created.

+1
source

All Articles