English 中文(简体)
直接将列表<String> 转换为列表<Integer>
原标题:Convert List<String> to List<Integer> directly

在解析我的文件“ s” 包含 AttritteGet: 1, 16, 10106, 10111 后, “ s” 包含 AtritteGet: 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(","));
}
最佳回答

不,你需要环绕阵列

for(String s : strList) intList.add(Integer.valueOf(s));
问题回答

使用 Java8 :

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

您可以使用 Java 8 的 Lambda 函数实现此目标, 而不循环

    String string = "1, 2, 3, 4";
    List<Integer> list = Arrays.asList(string.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());

使用 ambda:

strist. list. stream ().map (org.apache.commons.lang3.math.NumberUtils::toInt.)colum (Colectors.toList ()); (org.apache.commons.lang3.math.NumberUtils:::toInt.)colum (Colectors.toList ());

Guava 转换器

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

不,你将不得不循环 在每个元素:

for(String number : numbers) {
   numberList.add(Integer.parseInt(number)); 
}

发生这种情况的原因是没有直截了当的方法将一个类型的列表转换为 任何其他 类型。 有些转换是不可能的, 或需要以特定方式完成。 基本上, 转换取决于所涉及的对象和转换的背景, 因此不存在“ 一尺寸适合全部” 的解决方案。 例如, 如果您有一个 < code> Car 对象和一个 < code> person 对象, 您可以将一个 < code> List< Car> 转换为一个 < code> List & lt;Person> 直接, 因为它并不真正有意义 。

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

整个操作可能是这样的

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

如果您允许使用 Java 8 的羊羔, 您可以使用以下的代码样本 。

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

没有使用外部图书馆。 普通 < s> old new Java!

使用流和兰巴达:

newIntegerlist = listName.stream().map(x-> 
    Integer.valueOf(x)).collect(Collectors.toList());

上述代码行将把类型 List< string> 的列表转换为 List< Integer>

我希望这很有帮助。

不,没有办法(据我所知)在爪哇这样做。

基本上,你必须把每个条目从字符串转换为整数。

您重新寻找的东西可以用一种功能性更强的语言实现, 您可以通过一个转换函数, 并将其应用到列表的每个元素中... 但是这是不可能的( 它仍然适用于列表中的每一个元素 ) 。

<强>超能力:

不过,你可以使用Google Guava(http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Function.html)的功能模拟一种功能性更强的方法,如果这是你正在寻找的。

如果您担心对列表重复两次, 则使用调整器, 将每个整数符号转换为整数, 然后再添加到列表中 。

这是另一个展示瓜瓦力量的例子。 虽然这不是我写代码的方式,但我想把它包在一起,以显示瓜瓦为爪哇提供了什么样的功能性编程。

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

使用瓜瓦变换法如下:

列表 IntList = Lists. transform( 字符串列表, 整数: parseInt) ;

import java.util.Arrays; import java.util.Scanner;

公共类 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];
    }




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...