简体   繁体   中英

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>

My use case is a little different than this one

Is there any function that I can use in the place of mapNotNull in Java?

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

println(ints) // [45, 3]

Solution

There are no direct solution, but the equivalent of the code in java, can be:

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

Outputs

[45, 3]

More details

From the documentation:

fun String.toIntOrNull(): Int?

Parses the string as an Int number and returns the result or null if the string is not a valid representation of a number.

So if we want to create the exact code in java, then you can use:

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

And then:

mapNotNull

Returns a list containing only the non-null results of applying the given

Which lead you to use in java:

.filter(Objects::nonNull)

your final code should be:

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

But the first solution still the better one for your case.

Scanner is a nice way to check for the presence of integers:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM