[英]What is the best Alternative of mapNotNull (from Kotlin) in Java
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]
沒有直接的解決辦法,但是相當於java中的代碼,可以是:
List<Integer> ints = strings.stream()
.filter(s -> s.matches("[0-9]+"))
.map(Integer::valueOf)
.collect(Collectors.toList());
輸出
[45, 3]
從文檔:
fun String.toIntOrNull(): Int?
將字符串解析為 Int 數字,如果字符串不是數字的有效表示,則返回
result
或null
。
所以如果我們想在java中創建確切的代碼,那么你可以使用:
.map(s -> s.matches("[0-9]+") ? Integer.valueOf(s) : null)
進而:
返回僅包含應用給定的非空結果的列表
這導致您在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());
但是第一個解決方案仍然更適合您的情況。
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.