如何从 ArrayList<String> 中提取这些整数值

How to extract these integer values from ArrayList<String>

我有一个 ArrayList<String> abc,其中我得到这个值 [64.3, 25.1, 44.3, 34.2, 6.4, 48.5, 35.5, 59.5, 54.6, 26.6, 11.2, 50.3, 25.1]

现在我想从中提取整数值,例如 64,25,44,34,6,48,35,59,54,26,11,50,25 并将这些值放入整数数组 int[] cab

我怎样才能得到这个?如何从中删除小数点和小数点后的值?

  1. 字符串加倍

  2. double 到 int

    for(int i = 0 ; i < abc.size(); ++i) {
        tmp = Double.parseDouble(abc.get(i));
        cab[i] = (int)tmp;
        System.out.println(cab[i]);
    }
    

简单迭代:

int[] cab = new int[abc.size()];
for(int i = 0; i < cab.length; i++){
    cab[i] = (int)Float.parseFloat(abc.get(i));
}

在Java 8:

int[] cab = abc.stream()
        .map(Double::valueOf)
        .mapToInt(Double::intValue)
        .toArray();

试试这个:

Integer cab[] = new Integer[abc.size()];
cab= abc.toArray(cab);

//iterating array
for (Integer cabs: cab) {
System.out.println("cab= " + cabs);
}
ArrayList<Integer> newList = new ArrayList<Integer>(stringsList.size());
for (String myInt : strings){
    int intVal = (int)Double.parseDouble(myInt);
    newList.add(intVal);
}

其中 stringsList 是您的 Arraylist

使用此代码

Iterator itr = al.iterator();
          while(itr.hasNext()) {

             String s1=itr.next().toString();
             Double d=new Double(s1);
             int s2=d.intValue();
             System.out.print(s2 + " ");
          }

根据 Java 版本 and/or 偏好,这里有三种不同(但相似)的方法:

ArrayList<String> abc = new ArrayList<>(Arrays.asList(
        "64.3", "25.1", "44.3", "34.2", "6.4", "48.5", "35.5",
        "59.5", "54.6", "26.6", "11.2", "50.3", "25.1" ));
System.out.println("abc = " + abc);

// Loop (all Java versions)
int[] cab1 = new int[abc.size()];
for (int i = 0; i < cab1.length; i++)
    cab1[i] = (int)Double.parseDouble(abc.get(i));
System.out.println("cab1 = " + Arrays.toString(cab1));

// Java 8 stream with lambda expression
int[] cab2 = abc.stream()
                .mapToInt(v -> (int)Double.parseDouble(v))
                .toArray();
System.out.println("cab2 = " + Arrays.toString(cab2));

// Java 8 stream with method references
int[] cab3 = abc.stream()
                .map(Double::valueOf)
                .mapToInt(Double::intValue)
                .toArray();
System.out.println("cab3 = " + Arrays.toString(cab3));

输出

abc = [64.3, 25.1, 44.3, 34.2, 6.4, 48.5, 35.5, 59.5, 54.6, 26.6, 11.2, 50.3, 25.1]
cab1 = [64, 25, 44, 34, 6, 48, 35, 59, 54, 26, 11, 50, 25]
cab2 = [64, 25, 44, 34, 6, 48, 35, 59, 54, 26, 11, 50, 25]
cab3 = [64, 25, 44, 34, 6, 48, 35, 59, 54, 26, 11, 50, 25]