Convert List<String> to List<Integer> directly

浪尽此生 提交于 2019-12-29 04:05:08

问题


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(","));
}

回答1:


No, you need to loop over the array

for(String s : strList) intList.add(Integer.valueOf(s));



回答2:


Using Java8:

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



回答3:


Using lambda:

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




回答4:


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



回答5:


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.




回答6:


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.




回答7:


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



回答8:


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!




回答9:


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



回答10:


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.




回答11:


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



回答12:


You can consider code in my repo.

https://github.com/mohamedanees6/JavaUtils/wiki/CollectionUtils

castStringCollection(Collection<T>,Class)




回答13:


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.



来源:https://stackoverflow.com/questions/10706721/convert-liststring-to-listinteger-directly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!