|
||
|
||||
|
Here is a tutorial on how to use the java.util.Arrays class to sort Array values.
This example sorts an Array of Integers from the smallest to largest value: Java Code
import java.util.Arrays;
public class HowToSortAnArray {
public static void main(String[] args) {
//Array of Integers
int[] myIntArray = new int[]{20,100,69,4};
//SORTS ARRAY FROM SMALLEST TO LARGEST INT
Arrays.sort(myIntArray);
//for loop to print Array values to console
for (int a = 0; a < myIntArray.length; a++) {
System.out.println(myIntArray[a]);
}
}
}
//Output: 4 20 69 100
Java Code
import java.util.Arrays;
public class HowToSortAnArray {
public static void main(String[] args) {
String[] myStrArray = new String[] {"c", "b", "a", "D"};
//SORTS STRING ARRAY INTO CASE & THEN ALPHABETICAL ORDER
Arrays.sort(myStrArray);
//for loop to print int values to console
for (int a = 0; a < myStrArray.length; a++) {
System.out.println(myStrArray[a]);
}
}
}
//Output: D a b c
Java Code
import java.util.Arrays;
public class HowToSortAnArray {
public static void main(String[] args) {
String[] myStrArray = new String[] {"c", "b", "a", "D"};
//SORTS ARRAY INTO ALPHABETICAL ORDER
Arrays.sort(myStrArray, String.CASE_INSENSITIVE_ORDER);
//for loop to print int values to console
for (int a = 0; a < myStrArray.length; a++) {
System.out.println(myStrArray[a]);
}
}
}
//Output: a b c D
__________________
Don't forget to add syntax highlighted code tags around your code: [highlight=Java] code here [/highlight] Forum Tip: Add to peoples reputation ( ) by clicking the button on their useful posts.
|
![]() |
| Tags |
| java.util.arrays, sort arrays, sorting arrays |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Insert sort algorithm | Alysosh | Algorithms & Recursion | 1 | 26-05-2009 02:28 PM |
| java.util.UnknownFormatConversionException error | rosh72851 | Exceptions | 4 | 29-04-2009 03:53 PM |
| How to Populate all array values using the java.util.Arrays class | JavaPF | Java Code Snippets and Tutorials | 0 | 07-04-2009 10:31 AM |
| New to Java/struggling with arrays | Fendaril | Collections and Generics | 18 | 13-11-2008 12:31 PM |
| java.util.UnknownFormatConversionException error | rosh72851 | Exceptions | 2 | 08-10-2008 04:01 PM |