- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to 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));
- Related Articles
- How to Sort a String in Java alphabetically in Java?
- How to sort string array in android listview?
- How to sort a random number array in java?
- Java Program to Sort a String
- How to convert a Double array to a String array in java?
- How to sort Java array elements in ascending order?
- Sort String Array alphabetically by the initial character only in Java
- How to declare a static String array in Java
- how to convert Object array to String array in java
- How to sort an array with customized Comparator in Java?
- Sort Byte Array in Java
- How to create a string from a Java Array?
- Sort an Array of string using Selection sort in C++
- How to convert a byte array to hex string in Java?
- Java program to Sort long Array

Advertisements