可以使用 Java 8 的 Stream API 将 List 转换为 List,并保留 null 值。代码如下:

List<String> stringList = Arrays.asList('1', '2', '3', null);
List<Long> longList = stringList.stream()
        .map(s -> s == null ? null : Long.parseLong(s))
        .collect(Collectors.toList());

上面的代码先使用 Arrays.asList() 方法创建一个包含字符串和 null 值的 List,然后使用 stream() 方法将 List 转换为 Stream。接着使用 map() 方法将每个字符串转换为 Long 类型,如果字符串为 null,则直接返回 null。最后使用 collect() 方法将 Stream 转换为 List。

Java 将 List<String> 转换为 List<Long>,包含 null 值

原文地址: https://www.cveoy.top/t/topic/mixA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录