什么是Java中mapNotNull(来自Kotlin)的最佳替代方案?

3
inline fun <T, R : Any> Array<out T>.mapNotNull(
    transform: (T) -> R?
): List<R>

我的用例与这个有点不同

在Java中是否有我可以在mapNotNull位置使用的任何函数?

val strings: List<String> = listOf("12a", "45", "", "3")
val ints: List<Int> = strings.mapNotNull { it.toIntOrNull() }

println(ints) // [45, 3]
2个回答

6

解决方案

没有直接的解决方案,但是可以在Java中使用等效的代码:

List<Integer> ints = strings.stream()
        .filter(s -> s.matches("[0-9]+"))
        .map(Integer::valueOf)
        .collect(Collectors.toList());

输出

[45, 3]

更多细节

来自文档:

fun String.toIntOrNull(): Int?

将字符串解析为整数,并返回该结果null(如果该字符串不是数字的有效表示)。

因此,如果我们想要在Java中创建相同的代码,则可以使用:

.map(s -> s.matches("[0-9]+") ? Integer.valueOf(s) : null)

然后:

mapNotNull

返回一个列表,该列表仅包含应用给定函数后非空的结果。

这将引导您在Java中使用:

.filter(Objects::nonNull)

您的最终代码应该是:
List<Integer> ints = strings.stream()
        .map(s -> s.matches("[0-9]+") ? Integer.valueOf(s) : null)
        .filter(Objects::nonNull)
        .collect(Collectors.toList());

但第一种解决方案仍然是适合您情况的更好选择。


1

Scanner是一种检查整数是否存在的好方法:

List<String> strings = List.of("12a", "45", "", "3");
List<Integer> ints = strings.stream()
    .filter(it -> new Scanner(it).hasNextInt())
    .map(Integer::parseInt)
    .collect(Collectors.toList());

System.out.println(ints); // [45, 3]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接