
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort a String Array in Java
To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them.
One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of outer loop) to avoid repetitions in comparison.
Example
import java.util.Arrays; public class StringArrayInOrder { public static void main(String args[]) { String[] myArray = {"JavaFX", "HBase", "OpenCV", "Java", "Hadoop", "Neo4j"}; int size = myArray.length; for(int i = 0; i<size-1; i++) { for (int j = i+1; j<myArray.length; j++) { if(myArray[i].compareTo(myArray[j])>0) { String temp = myArray[i]; myArray[i] = myArray[j]; myArray[j] = temp; } } } System.out.println(Arrays.toString(myArray)); } }
Output
[HBase, Hadoop, Java, JavaFX, Neo4j, OpenCV]
You can also sort an array using the sort() method of the Arrays class.
String[] myArray = {"JavaFX", "HBase", "OpenCV", "Java", "Hadoop","Neo4j"}; Arrays.sort(myArray); System.out.println(Arrays.toString(myArray));
Advertisements