Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

599
Views
¿Cuál es la mejor alternativa de mapNotNull (de Kotlin) en Java?
inline fun <T, R : Any> Array<out T>.mapNotNull( transform: (T) -> R? ): List<R>

Mi caso de uso es un poco diferente a este

¿Hay alguna función que pueda usar en lugar de mapNotNull en 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 answers
Answer question

0

Solución

No hay una solución directa, pero el equivalente del código en Java puede ser:

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

Salidas

 [45, 3]

Más detalles

De la documentación:

fun String.toIntOrNull(): Int?

Analiza la cadena como un número Int y devuelve el result o null si la cadena no es una representación válida de un número.

Entonces, si queremos crear el código exacto en Java, puede usar:

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

Y luego:

mapNotNull

Devuelve una lista que contiene solo los resultados no nulos de aplicar el determinado

Lo que te lleva a usar en Java:

 .filter(Objects::nonNull)

su código final debe ser:

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

Pero la primera solución sigue siendo la mejor para su caso.

over 4 years ago · Santiago Trujillo Report

0

Scanner es una buena manera de verificar la presencia de números enteros:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!