java

How to Sort an Array in Java

Arrays can be sorted using Arrays class in java.util package.

If you don’t want to write a sorting algorithm yourself to sort an array, the java.util.Arrays class must first be imported. The method sort(Object [] a) is static and must therefore be called with the class name (without creating an object). It has no return value, but only sorts the array passed as a parameter.
 

Table of Contents

Primitive types

The primitive data types are sorted in ascending natural order:
 

Example 1 : Sort An Array Of Integer In Java
import java.util.Arrays;

public class ArraySortierenClass {

    public static void main(String[] args) {

        int[] arr = {9, 3, 1, 6, 2, 5};
        
        Arrays.sort(arr);
        
        System.out.println(Arrays.toString(arr)); 
    }
}

Output:

[1, 2, 3, 5, 6, 9]

Here the natural order of numbers is quite clear. In case of objects, it’s a bit more complicated: Is the “natural order”, e.g. for persons, sorting by last name, first name, or birth date?
 

java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More
Example 2 : Sort An Array Of String In Java
import java.util.Arrays;

public class ArraySortierenClass {

    public static void main(String[] args) {
        String[] name = new String[7];
        name[0] = "Philpe";
        name[1] = "Emily";
        name[2] = "Alex";
        name[3] = "Thomas";
        name[4] = "Ali";
        name[5] = "Yohan";
        name[6] = "Jean";
        
        Arrays.sort(name);
        
        for (int i = 0; i < name.length; i++) {
            System.out.println(name[i]);
        }
    }
}

Output:

Alex
Ali
Emily
Jean
Philpe
Thomas
Yohan


The Arrays.sort() method is overloaded and can accept different parameters, including of course primitive data types.
 

How to sort items in a stream with Stream sorted-minHow to sort items in a stream with Stream.sorted()Just like lists or arrays, you would also like to sort streams. Of course, the Java 8 Stream API offers a simple solution.   Sort…Read More
Objects

For objects such an order is only given if java.lang.Comparable interface is implemented. The String class implements the interface, so an array of type String can be sorted easily:

import java.util.Arrays;

public class ArraySortierenClass {

    public static void main(String[] args) {

        String[] name = {"Thomas", "Alex", "Emily"};
        
        Arrays.sort(name);
        
        System.out.println(Arrays.toString(name)); 
    }
}

Output:

[Alex, Emily, Thomas]

But be careful! Natural order does not mean alphabetical at the same time: When uppercase and lowercase letters are mixed, the uppercase letters come first and only then the lowercase letters:

import java.util.Arrays;

public class ArraySortierenClass {

    public static void main(String[] args) {

        String[] name = {"Thomas", "Yohan", "Emily", "alex"};
        
        Arrays.sort(name);
        
        System.out.println(Arrays.toString(name)); 
    }
}

Output:

[Emily, Thomas, Yohan, alex]


It is not compared alphabetically, as expected, but based on the Unicode values of the characters in the string.
 

How to compare two objects reference in JavaHow to compare two objects in JavaWhen are two objects “equal”? This question always causes confusion. The key to understanding it is to learn the difference between the relational operator ==…Read More
Sorting With Comparator

Alternatively, a comparator can be passed to sort() method. Comparator is an object that contains a method that specifies whether an object of a type is to be regarded as larger, smaller or the same size as another object.

The problem with strings that are not sorted alphabetically can now be solved as follows:

import java.util.Arrays;
import java.util.Comparator;

public class ArraySortierenClass {

    public static void main(String[] args) {

        String[] name = {"Thomas", "Yohan", "Emily", "alex"};
        
        Arrays.sort(name, new Comparator() {
            @Override
            public int compare(String first, String second) {
                return first.toLowerCase().compareTo(second.toLowerCase());
            }
        });
        
        System.out.println(Arrays.toString(name)); 
    }
} 

Output:

[alex, Emily, Thomas, Yohan]
Difference between == and .equalsDifference between == and .equals()In short: .equals() is used to compare objects, and the equal-to operator (==) is used to compare references and simple types such as int and…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *