Sorting Techniques in Java

JavaJavaBeginner
Practice Now

Introduction

Sorting is a vital operation in computer science, and Java provides different in-built methods to sort various data structures. Java has different classes available to sort different data structures. In this lab, we will explore sorting arrays, collections, and user-defined class instances.

Sorting Arrays

Arrays are a simple data structure that is used to store similar types of data in an ordered way. We can sort arrays using the built-in sort() method of the Arrays class.

The following code demonstrates sorting an array using the sort() method:

public static void main(String[] args) {
    int[] arr = {7, 9, 1, 0, 2, 5, 6, 11};
    System.out.println("Array Before Sorting: " + Arrays.toString(arr));
    Arrays.sort(arr);
    System.out.println("Array After Sorting: " + Arrays.toString(arr));
}

To run this code, navigate to the ~/project directory in the terminal and execute the following commands:

$ javac Sorting.java
$ java Sorting

This code will sort the array in ascending order. If you want to sort an array in descending order, you need to sort it using the Comparator interface.

Sorting Collections

Java provides the Collections class that has a sort() method to sort collections like lists, sets, and maps. The operating model of this function is similar to the sort() method of the Arrays class.

The following code demonstrates sorting a list of integers using the sort() method:

public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    list.add(6);
    list.add(3);
    list.add(8);
    list.add(1);
    list.add(9);

    System.out.println("List before sorting: " + list);

    Collections.sort(list);
    System.out.println("List after sorting: " + list);
}

To run this code, navigate to the ~/project directory in the terminal and execute the following commands:

$ javac Sorting.java
$ java Sorting

Sorting Sets

Sets are used to store unordered data without duplicates. We cannot sort sets directly using the sort() method of the Collections class. However, we can view the ordered data by transferring all the elements of the set to a list and then sorting the list.

The following code demonstrates sorting a set of integers using the sort() method:

public static void main(String[] args) {
    Set<Integer> set = new HashSet<Integer>();
    set.add(6);
    set.add(3);
    set.add(-2);
    set.add(1);
    set.add(9);

    List<Integer> list = new ArrayList<Integer>(set);
    Collections.sort(list);
    System.out.println("Set after sorting: " + list);
}

To run this code, navigate to the ~/project directory in the terminal and execute the following commands:

$ javac Sorting.java
$ java Sorting

The output of this code will be a sorted list of integers.

Sorting Maps

Maps are used to store key-value pairs. We can sort maps based on their keys or values. TreeMap can also be used to store key-value pairs in a sorted order.

The following code demonstrates sorting a map of integers using the sort() method:

public static void main(String[] args) {
    Map<Integer, String> map = new TreeMap<Integer, String>();
    map.put(6, "Apple");
    map.put(3, "Banana");
    map.put(1, "Mango");
    map.put(9, "Orange");

    System.out.println("Map before sorting: " + map);

    // Sorting by keys
    Map<Integer, String> sortedByKeyMap = new TreeMap<Integer, String>(map);
    System.out.println("Map after sorting by keys: " + sortedByKeyMap);

    // Sorting by value
    List<Map.Entry<Integer, String>> list = new ArrayList<Map.Entry<Integer, String>>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<Integer, String>>() {
        public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });

    Map<Integer, String> sortedByValueMap = new LinkedHashMap<Integer, String>();
    for (Map.Entry<Integer, String> entry : list) {
        sortedByValueMap.put(entry.getKey(), entry.getValue());
    }
    System.out.println("Map after sorting by values: " + sortedByValueMap);
}

To run this code, navigate to the ~/project directory in the terminal and execute the following commands:

$ javac Sorting.java
$ java Sorting

This code will sort the map by its keys and values.

Summary

This lab demonstrated how to sort different data structures in Java. We learned how to sort arrays, collections, and maps. We also learned how to sort user-defined class objects using the Comparable and Comparator interfaces. The sort() method of the Collections and Arrays classes were used to sort lists and arrays. Finally, we learned how to sort maps based on their values and keys.

Other Java Tutorials you may like