import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> stringList = Arrays.asList("1", "2", "3");
List<Integer> integerList = stringList.stream()
.map(Integer::parseInt)
.collect(Collectors.toList());
int sum = integerList.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("转换后的整数列表: " + integerList);
System.out.println("整数总和: " + sum);
}
}
- 首先通过
stringList.stream()
将List<String>
转换为流。
- 然后使用
map(Integer::parseInt)
将流中的每个String
元素转换为Integer
。
- 接着使用
collect(Collectors.toList())
将流转换回List<Integer>
。
- 对于计算总和,先将
List<Integer>
转换为IntStream
(通过mapToInt(Integer::intValue)
),然后使用sum()
方法计算总和。