Question:
Separate String and Int elements from an ArrayList - Java?
Marlon.Brando
2010-04-22 07:53:43 UTC
Lets say you have an arraylist of [1, 2, 3, 4, 5, a, b, c] i need to separate integers and strings and print them out. help!
Three answers:
deonejuan
2010-04-22 08:47:02 UTC
There are many ways. You don't show an ArrayList in your question. You show a String. If that's the case, RegEx and StringBuilder are the fastest and cleanest algo...



public class SortDemNumsOrAlphas {



public static void main(String[] args) {

String s = "[1, 2, 3, 4, 5, a, b, c]";

String ss = s.replaceAll( "[^A-Z0-9a-z]", "" );

System.out.println(ss);

String nums = ss.replaceAll( "[^0-9]", "" );

String alpha = ss.replaceAll( "[^A-Za-z]", "" );



System.out.println( newString( nums ));

System.out.println( newString( alpha));



}

private static String newString( String s ) {

StringBuilder sb = new StringBuilder();

sb.append( '[' );

for (int i = 0; i < s.length(); i++) {

sb.append( s.charAt( i ))

.append( "," )

.append( " ");



}

// take off last comma

int end = sb.lastIndexOf( "," );

sb.delete(end, sb.length() ).append( ']' );



return sb.toString( );

}

}

// otherwise

The wrapper Character has the following methods() in the API

Character.isLetterOrDigit( c );

Character.isLetter( c );

Character.isDigit( c );

// they all result in a boolean value

// you would use it like so

Character C = s.charAt(1);

if( Character.isDigit( C )) {



}
coderX
2010-04-22 09:06:52 UTC
The general idea is:



ArrayList has a remove method which returns the element removed, so make a for loop that runs through every element, removing every element and immediately prints them out before moving on to removing the next element.
2010-04-22 08:24:38 UTC
If they are all Strings, you can use Integer.parseInt(value) to parse your numbers to int and then wrap it in a try/catch to catch a NumberFormatException which would fire when they are not a number.



If they are mixed objects, then you will need to try casting them to int and then wrap it in a try/catch to catch a ClassCastException which would fire when they are not an int.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...