Convert List<String> to List<Integer> directly
JavaListCollectionsArraylistJava Problem Overview
After parsing my file "AttributeGet:1,16,10106,10111
So I need to get all the numbers after colon in the attributeIDGet ListList<String>
to List<Integer>
.
As the below code complains about Type mismatch, so I tried to do the Integer.parseInt, but I guess this will not work for List
private static List<Integer> attributeIDGet = new ArrayList<Integer>();
if(s.contains("AttributeGet:")) {
attributeIDGet = Arrays.asList(s.split(":")[1].split(","));
}
Java Solutions
Solution 1 - Java
Using Java8:
stringList.stream().map(Integer::parseInt).collect(Collectors.toList());
Solution 2 - Java
No, you need to loop over the array
for(String s : strList) intList.add(Integer.valueOf(s));
Solution 3 - Java
Using lambda:
strList.stream().map(org.apache.commons.lang3.math.NumberUtils::toInt).collect(Collectors.toList());
Solution 4 - Java
Guava Converters do the trick.
import com.google.common.base.Splitter;
import com.google.common.primitives.Longs;
final Iterable<Long> longIds =
Longs.stringConverter().convertAll(
Splitter.on(',').trimResults().omitEmptyStrings()
.splitToList("1,2,3"));
Solution 5 - Java
No, you will have to iterate over each element:
for(String number : numbers) {
numberList.add(Integer.parseInt(number));
}
The reason this happens is that there is no straightforward way to convert a list of one type into any other type. Some conversions are not possible, or need to be done in a specific way. Essentially the conversion depends on the objects involved and the context of the conversion so there is no "one size fits all" solution. For example, what if you had a Car
object and a Person
object. You can't convert a List<Car>
into a List<Person>
directly since it doesn't really make sense.
Solution 6 - Java
You can use the Lambda functions of Java 8 to achieve this without looping
String string = "1, 2, 3, 4";
List<Integer> list = Arrays.asList(string.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
Solution 7 - Java
If you use Google Guava library this is what you can do, see Lists#transform
String s = "AttributeGet:1,16,10106,10111";
List<Integer> attributeIDGet = new ArrayList<Integer>();
if(s.contains("AttributeGet:")) {
List<String> attributeIDGetS = Arrays.asList(s.split(":")[1].split(","));
attributeIDGet =
Lists.transform(attributeIDGetS, new Function<String, Integer>() {
public Integer apply(String e) {
return Integer.parseInt(e);
};
});
}
Yep, agree with above answer that's it's bloated, but stylish. But it's just another way.
Solution 8 - Java
Why don't you use stream to convert List of Strings to List of integers? like below
List<String> stringList = new ArrayList<String>(Arrays.asList("10", "30", "40",
"50", "60", "70"));
List<Integer> integerList = stringList.stream()
.map(Integer::valueOf).collect(Collectors.toList());
complete operation could be something like this
String s = "AttributeGet:1,16,10106,10111";
List<Integer> integerList = (s.startsWith("AttributeGet:")) ?
Arrays.asList(s.replace("AttributeGet:", "").split(","))
.stream().map(Integer::valueOf).collect(Collectors.toList())
: new ArrayList<Integer>();
Solution 9 - Java
If you're allowed to use lambdas from Java 8, you can use the following code sample.
final String text = "1:2:3:4:5";
final List<Integer> list = Arrays.asList(text.split(":")).stream()
.map(s -> Integer.parseInt(s))
.collect(Collectors.toList());
System.out.println(list);
No use of external libraries. Plain old new Java!
Solution 10 - Java
Using Streams and Lambda:
newIntegerlist = listName.stream().map(x->
Integer.valueOf(x)).collect(Collectors.toList());
The above line of code will convert the List of type List<String>
to List<Integer>
.
I hope it was helpful.
Solution 11 - Java
No, there is no way (that I know of), of doing that in Java.
Basically you'll have to transform each entry from String to Integer.
What you're looking for could be achieved in a more functional language, where you could pass a transformation function and apply it to every element of the list... but such is not possible (it would still apply to every element in the list).
Overkill:
You can, however use a Function from Google Guava (http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Function.html) to simulate a more functional approach, if that is what you're looking for.
If you're worried about iterating over the list twice, then instead of split use a Tokenizer and transform each integer token to Integer before adding to the list.
Solution 12 - Java
Here is another example to show power of Guava. Although, this is not the way I write code, I wanted to pack it all together to show what kind of functional programming Guava provides for Java.
Function<String, Integer> strToInt=new Function<String, Integer>() {
public Integer apply(String e) {
return Integer.parseInt(e);
}
};
String s = "AttributeGet:1,16,10106,10111";
List<Integer> attributeIDGet =(s.contains("AttributeGet:"))?
FluentIterable
.from(Iterables.skip(Splitter.on(CharMatcher.anyOf(";,")).split(s)), 1))
.transform(strToInt)
.toImmutableList():
new ArrayList<Integer>();
Solution 13 - Java
Use Guava transform method as below,
List
Solution 14 - Java
import java.util.Arrays; import java.util.Scanner;
public class reto1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double suma = 0, promedio = 0;
String IRCA = "";
int long_vector = Integer.parseInt(input.nextLine());
int[] Lista_Entero = new int[long_vector]; // INSTANCE INTEGER LIST
String[] lista_string = new String[long_vector]; // INSTANCE STRING LIST
Double[] lista_double = new Double[long_vector];
lista_string = input.nextLine().split(" "); // INPUT STRING LIST
input.close();
for (int i = 0; i < long_vector; i++) {
Lista_Entero[i] = Integer.parseInt(lista_string[i]); // CONVERT INDEX TO INDEX FROM STRING UNTIL INTEGER AND ASSIGNED TO NEW INTEGER LIST
suma = suma + Lista_Entero[i];
}