Nitin Gandhi
Nitin Gandhi

Reputation: 31

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]

Upvotes: 3

Views: 1919

Answers (2)

neu242
neu242

Reputation: 16575

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]

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

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.

Upvotes: 6

Related Questions