OneCompiler

[Java] How to sort an array?

I want to sory an array based on the elements, how can I do that in Java?

1 Answer

4 years ago by

We can use Arrays.sort to sort elements from an array. Following code shows how to do that

import java.util.Arrays;

public class JavaArrays {
	public static void main(String[] args) {
		String[] colors = { "blue", "red", "green", "yellow" };
		
		Arrays.sort(colors);
		
		System.out.println(Arrays.toString(colors));
	}
}

Output:

[blue, green, red, yellow]

Try this code online here: https://onecompiler.com/java/3xmt9gk4p

4 years ago by Karthik Divi