Java stream string array to int array

Convert a String Array to Integer Array in Java

Learn to convert a specified array of strings to an array of int or Integer values using Java 8 Streams. We will also learn to handle invalid values that cannot be parsed to integers.

1. Converting from String[] to int[]

Java Streams provide a concise way to iterate over array or collection elements, perform intermediate operations and collect the results into an entirely new collection or array.

In this approach, we iterate over the stream of string array, parse each string into int value using Integer::parseInt, and collect int values into a new array.

Notice we are using mapToInt() operation, which ensures we get only the int values to be collected using toArray() method.

String[] strArray = new String[] ; int[] intArray = Arrays.stream(strArray) .mapToInt(Integer::parseInt) .toArray(); System.out.println(Arrays.toString(intArray)); //Prints [1, 2, 3]

2. Converting from String[] to Integer[]

The conversion to Integer array is very similar to int array, except do not use the mapToInt() method that returns int array. Rather we use the map() method that returns the Object types and collects such integers to a new Integer array. The array type declaration has been given in toArray(Integer[]::new) method.

String[] strArray = new String[] ; Integer[] integerArray = Arrays.stream(strArray) .map(Integer::parseInt) .toArray(Integer[]::new); System.out.println(Arrays.toString(integerArray)); //Prints [1, 2, 3]

3. Handling Invalid Values

When we receive the string array values from a remote API or database, there are always chances of getting unparsable values. In this case, we must handle the ParseException when we are parsing string values to int values, and determine a default value to denote an invalid value in the integer array.

In the following example, when we get an unparsable String value, we return the integer value -1. You can choose another default value based on your usecase.

String[] invalidStrArray = new String[]; int[] intArray = Arrays.stream(invalidStrArray).mapToInt(str -> < try < return Integer.parseInt(str); >catch (NumberFormatException nfe) < return -1; >>).toArray(); System.out.println(Arrays.toString(intArray)); //Prints [1, 2, 3, -1, 5]

In this short Java tutorial, we learned to convert a String array into Integer array. We can use this technique to parse and collect the string values to other number types, such as long or double.

Источник

Converting a String Array Into an int Array in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

Читайте также:  Запуск venv python linux

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Читайте также:  Где хранятся сертификаты в java

Connect your cluster and start monitoring your K8s costs right away:

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

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this quick tutorial, let’s explore how to convert an array of String into an array of int in Java.

2. Introduction to the Problem

First of all, let’s see a String array example:

String[] stringArray = new String[] < "1", "2", "3", "4", "5", "6", "42" >;

We’ve created stringArray with seven strings. Now, we need to convert stringArray into an integer array:

As the example above shows, the requirement is pretty straightforward. However, in the real world, the string array may come from different sources, such as user input or another system. Therefore, the input array may contain some values that are not in valid number formats, for instance:

String[] stringArrayWithInvalidNum = new String[] < "1", "2", "hello", "4", "world", "6", "42" >;

The “hello” and “world” elements aren’t valid numbers, though the others are. Usually, when these kinds of values are detected in an actual project, we’ll follow special error handling rules — for instance, aborting the array conversion, taking a particular integer as a fallback, and so on.

In this tutorial, we will use Java’s minimum integer as the fallback for invalid string elements:

int[] expectedWithInvalidInput = new int[] < 1, 2, Integer.MIN_VALUE, 4, Integer.MIN_VALUE, 6, 42 >;

Next, let’s start with the string array with all valid elements and then extend the solution with the error-handling logic.

For simplicity, we’ll use unit test assertions to verify if our solutions work as expected.

3. Using the Stream API

Let’s first convert the string array with all valid elements using the Stream API:

int[] result = Arrays.stream(stringArray).mapToInt(Integer::parseInt).toArray(); assertArrayEquals(expected, result);

As we can see, the Arrays.stream() method turns the input string array into a Stream. Then, the mapToInt() intermediate operation converts our stream to an IntStream object.

We’ve used Integer.parseInt() to convert strings to integers. Finally, toArray() converts the IntStream object back to an array.

So, next, let’s look at the elements in an invalid number format scenario.

Suppose the input string’s format is not a valid number, in which case the Integer.parseInt() method throws NumberFormatException.

Therefore, we need to replace the method reference Integer::parseInt in the mapToInt() method with a lambda expression and handle the NumberFormatException exception in the lambda expression:

int[] result = Arrays.stream(stringArrayWithInvalidNum).mapToInt(s -> < try < return Integer.parseInt(s); >catch (NumberFormatException ex) < // logging . return Integer.MIN_VALUE; >>).toArray(); assertArrayEquals(expectedWithInvalidInput, result);

Then, if we run the test, it passes.

Читайте также:  JavaScript Loan Calculator

As the code above shows, we’ve only changed the implementation in the mapToInt() method.

It’s worth mentioning that Java Stream API is available on Java 8 and later versions.

4. Implementing the Conversion in a Loop

We’ve learned how the Stream API solves the problem. However, if we’re working with an older Java version, we need to solve the problem differently.

Now that we understand Integer.parseInt() does the main conversion job, we can loop through the elements in the array and call the Integer.parseInt() method on each string element:

int[] result = new int[stringArray.length]; for (int i = 0; i < stringArray.length; i++) < result[i] = Integer.parseInt(stringArray[i]); >assertArrayEquals(expected, result);

As we can see in the implementation above, we first create an integer array with the same length as the input string array. Then, we perform the conversion and fill the result array in the for loop.

Next, let’s extend the implementation to add the error-handling logic. Similar to the Stream API approach, just wrapping the conversion line by a try-catch block can solve the problem:

int[] result = new int[stringArrayWithInvalidNum.length]; for (int i = 0; i < stringArrayWithInvalidNum.length; i++) < try < result[i] = Integer.parseInt(stringArrayWithInvalidNum[i]); >catch (NumberFormatException exception) < // logging . result[i] = Integer.MIN_VALUE; >> assertArrayEquals(expectedWithInvalidInput, result);

The test passes if we give it a run.

5. Conclusion

In this article, we’ve learned two ways to convert a string array to an integer array through examples. Moreover, we’ve discussed handling the conversion when the string array contains invalid number formats.

If our Java version is 8 or later, the Stream API would be the most straightforward solution to the problem. Otherwise, we can loop through the string array and convert each string element to an integer.

As usual, all code snippets presented in the article are available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью