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

600
Views
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 answers
Answer question

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 Report

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 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!