Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

602
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda