Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

Often, when working with several programming scenarios, there will be strings that contain numbers, and it might be necessary to find the greatest among these values.

In this tutorial, we’ll delve into different ways and Java code illustrations for properly identifying and extracting the greatest numeric value from a given string.

2. String Parsing with Comparison

The simplest method includes reading the strings and identifying the numeric substrings. We can detect the largest number through a comparison of the prefixes. Let’s take an example:

String inputString = "The numbers are 10, 20, and 5";
int expectedLargestNumber = 20;

@Test
void givenInputString_whenUsingBasicApproach_thenFindingLargestNumber() {
    String[] numbers = inputString.split("[^0-9]+");

    int largestNumber = Integer.MIN_VALUE;
    for (String number : numbers) {
        if (!number.isEmpty()) {
            int currentNumber = Integer.parseInt(number);
            if (currentNumber > largestNumber) {
                largestNumber = currentNumber;
            }
        }
    }
    assertEquals(expectedLargestNumber, largestNumber);
}

Here, we first use the split() method to split the input string named inputString into an array of sub-strings. Such division takes place through a regular expression, [^0-9]+, that intercepts only digits in the string.

Subsequently, a regular loop illustrates the string splitting. The loop restricts the array to having the resulting substrings and, on purpose, no empty strings. The implementation of each non-empty substring contains a prominent conversion with the Integer.parseInt() method.

Afterwards, a comparison between the current numeric value and the largestNumber found so far takes place, and an update happens in case a larger value is encountered. Finally, we use the assertEquals() method to ensure that the largestNumber is equal to the expectedLargestNumber.

3. Efficient Numeric Extraction with Regular Expressions

Regular expressions are the ones that allow us to extract the numeric values from a string concisely and effectively. Taking advantage of the Pattern and Matcher classes, we thus make the process more streamlined. Here’s a simple example:

@Test
void givenInputString_whenUsingRegularExpression_thenFindingLargestNumber() {
    Pattern pattern = Pattern.compile("\\d+");
    Matcher matcher = pattern.matcher(inputString);

    int largestNumber = Integer.MIN_VALUE;
    while (matcher.find()) {
        int currentNumber = Integer.parseInt(matcher.group());
        if (currentNumber > largestNumber) {
            largestNumber = currentNumber;
        }
    }
    assertEquals(expectedLargestNumber, largestNumber);
}

Here, we start by compiling a regular expression (\d+) using the Pattern.compile() method. This expression is meticulously designed to focus on matching one or more digits within the input string.

Then, we initialize the Matcher object, denoted as a matcher, by applying the compiled pattern to the inputString.

Afterward, we enter a subsequent while loop. The numeric value is extracted within each iteration using the Integer.parseInt(matcher.group()) method. A crucial comparison unfolds, assessing this current numeric value against the existing largestNumber. Should a larger value be discovered, the largestNumber is promptly updated to reflect this identification.

4. Stream and Lambda Expressions

Java 8 proposes the Stream API and lambda expression; therefore, the code is more compact and easier-to-read.

Let’s take a simple implementation:

@Test
void givenInputString_whenUsingStreamAndLambdaExpression_thenFindingLargestNumber() {
    int largestNumber = Arrays.stream(inputString.split("[^0-9]+"))
      .filter(s -> !s.isEmpty())
      .mapToInt(Integer::parseInt)
      .max()
      .orElse(Integer.MIN_VALUE);

    assertEquals(expectedLargestNumber, largestNumber);
}

In this test method, we begin by filtering the string to extract its numeric components exclusively, which is achieved through the utilization of the split() method. Additionally, we incorporate measures to address the potential occurrence of an empty stream, implementing the isEmpty() method.

Following the initial filtering, we leverage the mapToInt() method to systematically convert each non-empty substring into an integer, facilitated by the Integer::parseInt reference. Subsequently, the max() operation efficiently identifies the largest integer value present within the processed stream.

We employ the orElse() method to wrap up the streamlined approach, strategically setting the default value to Integer.MIN_VALUE.

5. Conclusion

In conclusion, this tutorial is a thorough examination of techniques that make it easier to work with strings containing numbers in Java.

As always, the complete code samples for this article can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.