Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List<String> to List<Integer>?

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?

like image 486
Shashi Avatar asked Dec 01 '22 18:12

Shashi


2 Answers

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));
}
like image 114
f1sh Avatar answered Dec 10 '22 11:12

f1sh


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.

like image 26
Philipp Avatar answered Dec 10 '22 11:12

Philipp