I am getting String of constants in List<String>
. I need List<Integer>
. By the basic way,
I will iterate and cast into Integer.
Is there any better solution?
Nope, there's no other way.
But casting is not possible in this case, you need to do use Integer.parseInt(stringValue)
.
List<String> listStrings = ...
List<Integer> listIntegers = new ArrayList<Integer>(listStrings.size());
for(String current:listStrings){
listIntegers.add(Integer.parseInt(current));
}
There is a way to do this.
You could use the Adapter Pattern and create a class which implements List<Integer>
, but internally accesses your List<String>
casting the values between Integer and String. As long as you fulfill all the contracts, any API which requires a List<Integer>
will be able to work with this class just like with a native List<Integer>
.
This might seem cumbersome and inefficient, but when you need to pass a List<Integer>
to an API which only accesses some values of the list, it can be more efficient to cast some of them on-demand ("lazy evaluation") instead of casting all of them. It also saves memory, because you won't have both the string- and the integer representation of your whole list in memory at the same time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With