Java ArrayList String to Integer

This tutorial will convert a Java ArrayList from Strings to an ArrayList of integers. In Java programming you may get an ArrayList from a shared method that contains strings which are actually numbers, but your application needs manipulate actual numbers. I see this happening a lot when a program reads in config parameters and stores them as strings. Java has a method to change a string into an array.


Convert String to Integer

The Integer class comes with a method called parseInt() that will take a string as input and output it to an integer. The one liner below will take converts the string to an integer and at the same time stores it in our ArrayList of integers.

jcdIntegerArrayList.add(Integer.parseInt(str));


Java ArrayList String to Integer Sample Code

Here is the full Java source code that defines an ArrayList of Strings and then converts that to an ArrayList of Integers.

package com.jcd.java.tutorials;

import java.util.ArrayList;

public class JavaConvertArrayList 
{

	public static void main(String[] args) 
	{

		//Define a string of textual numbers
		String[] jcdStrings  = {"100","110","120","130","140","150","160","170","180","190","200"};
		
		//Create an empty ArrayList to hold String
		ArrayList<String> jcdStringArrayList = new ArrayList<String>();
		
		System.out.println("Printing ArrayList of Strings:");
		
		//Store our textnumbers in the ArrayList
		for(String str : jcdStrings)
		{
			jcdStringArrayList.add(str);
		}
		
		//Print out the ArrayList of strings
		for(String str : jcdStringArrayList)
		{
			System.out.println(str);
		}
		
		//Create an empty ArrayList to hold Integers
		ArrayList<Integer> jcdIntegerArrayList = new ArrayList<Integer>();
		
		//Loop through the ArrayList of strings and populate ArrayList of integers
		for(String str : jcdStringArrayList)
		{
			jcdIntegerArrayList.add(Integer.parseInt(str));
		}
		
		System.out.println("\nPrinting ArrayList of Integers:");
		
		//Print out the ArrayList of integers
		for(Integer integer : jcdIntegerArrayList)
		{
			System.out.println(integer);
		}

	}

}

Below is the output after compiling and running the sample Java code

Printing ArrayList of Strings:
100
110
120
130
140
150
160
170
180
190
200

Printing ArrayList of Integers:
100
110
120
130
140
150
160
170



Java References:

Add a Comment

Your email address will not be published. Required fields are marked *