簡體   English   中英

Java 中 mapNotNull(來自 Kotlin)的最佳替代品是什么

[英]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 數字,如果字符串不是數字的有效表示,則返回resultnull

所以如果我們想在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());

但是第一個解決方案仍然更適合您的情況。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM