Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

601
Vistas
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]
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar

0

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]
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda