[java] Convert List<String> to List<Integer> directly

After parsing my file " s" contains AttributeGet:1,16,10106,10111

So I need to get all the numbers after colon in the attributeIDGet List. I know there are several ways to do it. But is there any way we can Directly convert List<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. Here s is String.

private static List<Integer> attributeIDGet = new ArrayList<Integer>();

if(s.contains("AttributeGet:")) {
    attributeIDGet = Arrays.asList(s.split(":")[1].split(","));
}

This question is related to java list collections arraylist

The answer is


Using lambda:

strList.stream().map(org.apache.commons.lang3.math.NumberUtils::toInt).collect(Collectors.toList());


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.


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.


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"));

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());

Using Java8:

stringList.stream().map(Integer::parseInt).collect(Collectors.toList());

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.


Use Guava transform method as below,

List intList = Lists.transform(stringList, Integer::parseInt);


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.


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>();

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!


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>();

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable