我有一个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
我怎么能得到这个?如何从中删除小数和小数后的值?
答案 0 :(得分:3)
以下是三种不同(但相似)的方法,具体取决于Java版本和/或首选项:
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]
答案 1 :(得分:1)
简单地迭代:
int[] cab = new int[abc.size()];
for(int i = 0; i < cab.length; i++){
cab[i] = (int)Float.parseFloat(abc.get(i));
}
答案 2 :(得分:1)
试试这个:
Integer cab[] = new Integer[abc.size()];
cab= abc.toArray(cab);
//iterating array
for (Integer cabs: cab) {
System.out.println("cab= " + cabs);
}
答案 3 :(得分:0)
字符串加倍
double to int
for(int i = 0 ; i < abc.size(); ++i) {
tmp = Double.parseDouble(abc.get(i));
cab[i] = (int)tmp;
System.out.println(cab[i]);
}
答案 4 :(得分:0)
在Java 8中:
int[] cab = abc.stream()
.map(Double::valueOf)
.mapToInt(Double::intValue)
.toArray();
答案 5 :(得分:0)
ArrayList<Integer> newList = new ArrayList<Integer>(stringsList.size());
for (String myInt : strings){
int intVal = (int)Double.parseDouble(myInt);
newList.add(intVal);
}
其中stringsList是你的Arraylist
答案 6 :(得分:0)
使用此代码
$query->formatResults(function (\Cake\Datasource\ResultSetInterface $results) {
return $results->map(function ($row) {
$row['url'] = array(
'controller' => 'content',
'action' => 'view',
$row['slug'],
$row['content_type']['alias']
);
return $row;
});
});