settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Sort an array for integers and strings

+13 votes

How can I sort an array in Java - for numbers and for strings (let's say in alphabetical order)?

Are there any methods of some classes which can be used?

Thanks

asked in Java category by user eiorgert
edited by user golearnweb

1 Answer

+1 vote
 
Best answer

You can use the Class Array and it's method .sort();

Inside the sort brackets put your array's name and it will sort it;

This method can be used for sorting integers and strings - in alphabetical order as you wish :-)

Here is the code (SEE LINES 13 & 28):

package com.tutorials7.java.useful_codes;

import java.util.Arrays;

public class SortArray {
    public static void main(String[] args) {
        System.out.println("Array ints[] WITHOUT sorting:");
        int[] ints = {30, 14, 5, 0, 743432};
        for (int i = 0; i < ints.length; i++) {
            System.out.println(ints[i]);
        }

        Arrays.sort(ints);//Class Arrays and it's METHOD FOR SORTING ARRAYS CALLED .sort()

        System.out.println("Array ints[] WITH sorting:");
        for (int i = 0; i < ints.length; i++) {
            System.out.println(ints[i]);
        }

        System.out.println("////////////////////////////////////////////////");

        System.out.println("Array stringsArray[] WITHOUT sorting:");
        String[] stringsArray = {"R", "A", "S", "F", "B", "N", "A", "L"};
        for (String s : stringsArray) {
            System.out.println(s);
        }

        Arrays.sort(stringsArray);//SORTS THE ARRAY IN ALPHABETICAL ORDER

        System.out.println("Array stringsArray[] WITH sorting:");
        for (String stringValue : stringsArray) {
            System.out.println(stringValue);
        }
    }
}

Here's the output:

Array ints[] WITHOUT sorting:
30
14
5
0
743432
Array ints[] WITH sorting:
0
5
14
30
743432
////////////////////////////////////////////////
Array stringsArray[] WITHOUT sorting:
R
A
S
F
B
N
A
L
Array stringsArray[] WITH sorting:
A
A
B
F
L
N
R
S

Process finished with exit code 0

answered by user hues
selected by user golearnweb
...