Maison >Java >javaDidacticiel >Tri en Java
Syntaxe pour les tableaux :
Arrays.sort(array_name);
Pour les collections
Commencez votre cours de développement de logiciels libres
Développement Web, langages de programmation, tests de logiciels et autres
Collections.sort(array_name_list);
Voici les points suivants :
Vous trouverez ci-dessous quelques-unes des manières par lesquelles le tri peut être effectué dans le tri en Java :
Ceci est utilisé pour trier le tableau complet par ordre croissant. Par défaut, cette méthode trie les éléments du tableau par ordre croissant.
Code :
import java.util.Arrays; public class SimpleSort { public static void main(String[] args) { //Unsorted array of numbers Integer[] arr = new Integer[] {100, 20, 10, 30, 80, 70, 90, 40, 50, 60}; //Sort function to sort the above array Arrays.sort(arr); //Printing the sorted array on console System.out.println(Arrays.toString(arr)); } }
Sortie :
Cette méthode en Java est utilisée pour trier le tableau dans l'ordre inverse ou décroissant. Il existe des scénarios dans lesquels nous devons trier les éléments par ordre décroissant, et Java le fait via la méthode intégrée.
Code :
import java.util.Arrays; public class ReverseSort { public static void main(String[] args) { //Unsorted array of numbers Integer[] arr = new Integer[] { 100, 20, 10, 30, 80, 70, 90, 40, 50, 60}; //Sort function to sort the above array Arrays.sort(arr, Collections.reverseOrder()); //Printing the sorted array on console System.out.println(Arrays.toString(arr)); } }
Sortie :
S'il est nécessaire de trier une partie d'un tableau au lieu de l'ensemble du tableau, Java offre la possibilité de trier ce type de tableau en spécifiant 3 paramètres, c'est-à-dire le nom du tableau, le premier index à partir duquel le tri doit être démarré. et le dernier index jusqu'au moment où le tri doit être effectué.
Code :
import java.util.Arrays; public class ReverseSort { public static void main(String[] args) { //Unsorted array of numbers Integer[] arr = new Integer[] { 100, 20, 10, 30, 80, 70, 90, 40, 50, 60}; //Sort function to sort the above array Arrays.sort(arr, 1, 5); //Printing the sorted array on console System.out.println(Arrays.toString(arr)); } }
Sortie :
From Java 8, the new API of the parallel sort has been released. Basically, in Parallel sort, the array is divided into 2 sub-arrays, and then the basic Array.sort() function is performed by a separate thread. The sorted arrays are then merged in the end to form the fully sorted array. This is done to leverage the use of multi-threading.
Code:
import java.util.Arrays; public class ParallelSort { public static void main(String[] args) { //Unsorted array of numbers Integer[] arr = new Integer[] { 100, 20, 10, 30, 80, 70, 90, 40, 50, 60}; //parallel Sort function to sort the above array Arrays.parallelSort(arr); //Printing the sorted array on console System.out.println(Arrays.toString(arr)); } }
Output:
Like a normal Array.sort(), Arrays.parallelSort() also provides the facility to sort a particular range of array or sorting an array in reverse order.
Syntax:
// to Sort a range of array by parallelsort Arrays.parallelSort(array_name, findex, lindex); // to sort an array in reverse order using parallelSort Arrays.parallelSort(array_name, Collections.reverseOder());
This method is used to sort the collections like list, map, Set, etc. It uses the merge sort and gives the same complexity as Array.sort(), i.e. O(n(logn)).
Code:
import java.util.Arrays; import java.util.Collections; public class ListSort { public static void main(String[] args) { //Unsorted list Integer[] arr = new Integer[] { 100, 20, 10, 30, 80, 70, 90, 40, 50, 60 }; List<Integer> arrList = Arrays.asList(arr); //Sorting of list using the method Collections.sort(arrList); //Printing the list sorted above System.out.println(arrList); } }
Output:
Code:
import java.util.Arrays; import java.util.Collections; public class ListSortRev { public static void main(String[] args) { //Unsorted array list of Integers Integer[] arr = new Integer[] {100, 20, 10, 30, 80, 70, 90, 40, 50, 60 }; List<Integer> arrList = Arrays.asList(arr); //Sorting of list using the method Collections.sort(arrList); //Printing the list sorted above System.out.println(arrList); } }
Output:
There are 3 basic rules while sorting a collection ‘Set’ using the above method sort(array_name):
Code:
List<Integer> numList = new ArrayList<Integer>(num) ; //Sorting the list retrieved above Collections.sort(numList); // Converting sorted List into Set num = new LinkedHashSet<>(numList); //Printing the Resulting Set on console System.out.println(num); } }
Output:
Collection Map in Java is a combination of key and value So sorting can be done both ways, either through key or by value.
Code:
import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class SortHashKey { public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<>(); map.put(80, "Akshay"); map.put(20, "Akash"); map.put(10, "Bob"); map.put(30, "Nitika"); map.put(90, "Yashi"); map.put(100, "Dragisa"); TreeMap<Integer, String> treeMap = new TreeMap<>(map); System.out.println(treeMap); } }
Output:
One of the easiest ways to sort the elements of the Map by Keys is by adding the unsorted map elements in the TreeMap. TreeMap automatically sorts the elements in the ascending order of Hash Keys. Though collection.sort() can also be used to do the same, it is somewhat complex and needs to be coded well.
Code:
import java.util.HashMap; import java.util.Map; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.Map; public class SortHashValue { public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<>(); map.put(80, "Akshay"); map.put(20, "Akash"); map.put(10, "Bob"); map.put(30, “Nitika"); map.put(90, "Yashi"); map.put(100, "Dragisa"); LinkedHashMap<Integer, String> sorted = new LinkedHashMap<>(); map.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) .forEachOrdered(x -> sorted.put(x.getKey(), x.getValue()));
Output:
In the above example of sorting of Map by value, firstly we set the entries using the map.entrySet() and then stream of those entries using stream() method, call the sorted array using sorted() method by comparing by value in the pair. for each ordered() is used to traverse the stream to produce the result.
Comparable is an Interface, and it makes the classes comparable to its instances.
To compare the two instances of the same class, Comparable interface needs to be implemented, and the method compareTo() needs to be overridden. The classes that implement this interface, its list of objects are sorted automatically using the method Collections.sort() and Arrays.sort().
Code:
ArrayList<Employee> list = new ArrayList<>(); // Adding the instance objects of class Employee in list list.add(new Employee(10, "Akshay"))); list.add(new Employee(40, "Bob"))); list.add(new Employee(20, "Priyansh"))); list.add(new Employee(50, "Chandni"))); list.add(new Employee(70, "Yashi"))); Collections.sort(list); // Printing the sorted list on Console System.out.println(list);
Output:
The Sorting in Java methods used in Java for multiple scenarios of Arrays and Collections are explained above. A programmer needs to keep in mind how the sort() method should be used for different Collection types. With Java 8, sorting can also be done through Lambdas to implement the Comparator interface, which makes the sorting easier. Though it is a bit difficult to learn all of them, it can be easy working with them if all the basic concepts of Java, especially data streaming, Arrays, and Collections, are clear. Though sorting Algorithms are evergreen and can be easily implemented in Java-like other programming languages, they have varying complexity, and the in-built function sort() of Java makes things easier if the basic concepts are learned by heart.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!