Java сортировка массива string

Sorting Arrays in Java

Learn to sort a Java array of primitives, strings and custom objects in multiple ways with the help of Comparable and Comparator interfaces, Arrays.sort() and Stream.sorted() APIs.

We will learn to sort arrays in natural ordering, reverse ordering and any other custom ordering as well.

1. Basics of Array Sorting

The basic concepts behind the sorting feature remain the same no matter which Java API we use to sort.

  • All inbuilt APIs support the sorting with the natural order by default. Numerical types are sorted in ascending order, strings are sorted in dictionary order (lexicographically) and custom objects are sorted by the order implemented by the Comparable interface.
  • To sort in the reverse order, we can use Comparator.reverseOrder() to the sort methods.
  • To sort in the custom order, we must create an instance of the Comparator interface and provide the relevant sorting behavior in it. Then we will pass an instance of the comparator into the sort API.

Now let’s dive into the java programs demonstrating the sorting of arrays. For custom sorting, we will use the instances of User class. Note that the default sorting is supported on the id field.

public class User implements Comparable  < public long id; public String firstName; public String lastName; //Add getters and setters @Override public int compareTo(final User user) < if(user == null ) < return -1; >else < return (int)(this.id - user.id); >> >

2. Arrays.sort() and Arrays.parallelSort()

The java.util.Arrays class provides many utilities static methods. The sort() APis are also such methods that helps in sorting a given array of items.

The sort() API implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted. It offers the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons.

The parallelSort() API implementation is a Dual-Pivot quicksort that offers O(n log(n)) performance on all data sets, and is typically faster than traditional (one-pivot) quicksort implementations.

public static void sort(array, ?comparator) public static void parallelSort(array, ?comparator)

2.1. Sorting in Natural Order

Java program to sort a String array in default order. Note that String class has implemented the Comparable interface, already.

String[] tokens = ; Arrays.sort(tokens); //[A, B, C, D, E]

2.2. Sorting in Reverse Order

Java program to use the Comparator.reverseOrder() to reverse the natural ordering.

String[] tokens = ; Arrays.sort(tokens, Collections.reverseOrder()); //[E, D, C, B, A]

We are sorting the users array by their first name.

User[] users = getUsersArray(); Comparator firstNameSorter = Comparator.comparing(User::getFirstName); Arrays.sort(users, firstNameSorter);

To sort on multiple fields, like SQL group by clause, we can create a complex Comparator instance and use it for sorting purposes.

Comparator fullNameSorter = Comparator.comparing(Employee::getFirstName) .thenComparing(Employee::getLastName); Arrays.sort(employees, fullNameSorter);

3. Sorting Arrays using Stream API

Читайте также:  Php var www ssl

We can sort the array of primitives or custom objects using the Stream.sorted() method in a very similar way we used the Arrays.sort() API.

  • The sorted() API returns a stream consisting of the elements of this stream, sorted according to the natural order.
  • If the elements of this stream are not Comparable , a java.lang.ClassCastException may be thrown when the terminal operation is executed.
  • It also accepts an optional comparator instance that is used for implementing the custom sorting behavior.

For ordered streams (stream is generated from an ordered collection such as ArrayList), the sort is stable. For unordered streams (for example, streams generated from HashMap), no stability guarantees are made.

Stream sorted() Stream sorted(?comparator)
//1. Natural ordering User[] sortedUserArray = Stream.of(userArray) .sorted() .toArray(User[]::new); //2. Reverse ordering User[] sortedUserArray = Stream.of(userArray) .sorted(Comparator.reverseOrder()) .toArray(User[]::new); //3. Custom Sorting Comparator nameComparator = Comparator.comparing(Employee::getName) .thenComparing(Employee::getId) User[] sortedUserArray = Stream.of(userArray) .sorted(nameComparator) .toArray(User[]::new);

In this given example, we learned to sort an array using Arrays.sort() and Stream APIs. We learned to sort in natural order, reverse order as well as in custom order.

Источник

Java сортировка массива string

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Sort String Array in Java

Sort String Array in Java

Sorting is a very important feature in programming as it sets the different elements of an array in the required order. Generally, people use alphabetical order or increasing or decreasing orders. Sorting is generally done to convert a raw and unorganized form of data into proper and organized order for making it meaningful for the human brain. There are two methods for performing sorting string array. The first method is called custom sorting or user-defined logic sorting and the second method is called natural sorting or Array.sort() sorting. In this article both the methods are explained using multiple examples and their working. In this topic, we are going to learn about Sort String Array in Java.

Web development, programming languages, Software testing & others

Methods and Examples of Sorting String Array in Java

Here are the following examples and methods mentioned below

1. Using User-Defined Logic or custom sorting

Sorting can be done by comparing each and every element individually with the rest of the elements. In the first example, the same process is performed. There are two loops used, the repetitions while performing comparison is avoided by the inner loop. When the condition (favouritefood[a].compareTo(favouritefood[b])>0) results true than 0,now the program performs the swapping and array sorting is done. Similarly, all of the elements of the array are checked using the condition and the sorting is completed. In this example, the elements are sorted in an alphabetical order using user-defined logic or custom sorting.

Читайте также:  Postgresql connector java maven
Example #1
import java.util.Arrays; public class Sortingexample1 < public static void main( String args[]) < String[] favouritefood = ; System.out.print(" Rahul favourite foods are: \n " ); int length = favouritefood.length; for(int a = 0 ; a0) < String virtual = favouritefood[a]; favouritefood[a] = favouritefood[b]; favouritefood[b] = virtual; >> > System.out.println( Arrays.toString( favouritefood )); > >

Sort String Array in Java output 1

Example #2

This example has been performed using three simple steps. Firstly, using loop we have to convert the input string into a character array. Now, Arrays.sort(array1, new Comparator () is used to sort the character array. Here the compare() method is used according to the behavior of the custom sorting. Now, use the StringBuilder to create a string from the character array.

import java.util.Arrays; import java.util.Comparator; public class Sortingexample2 < public static String sortString( String initialstringused ) < System.out.println( " Mixed kinda character string used \n " ); Character array1[] = new Character[ initialstringused.length() ]; for (int a = 0 ; a < initialstringused.length() ; a++) < array1[a] = initialstringused.charAt(a); >System.out.println( " We use character string here \n " ); Arrays.sort( array1, new Comparator() < @Override public int compare(Character FirstInput, Character SecondInput) < return Character.compare(Character.toUpperCase(FirstInput), Character.toUpperCase(SecondInput)); >>); StringBuilder b = new StringBuilder(array1.length); for ( Character c : array1 ) b.append( c.charValue() ); return b.toString(); > public static void main(String[] args) < String initialstringused = " \n Biryani is loved by Rahul \n "; String stringwegetinreturn = sortString( initialstringused ); System.out.println( " Got an output as : \n " + stringwegetinreturn ); System.out.println( " \n Initial sentence entered was : \n " + initialstringused ); >>

Sort String Array in Java output 2

2. Using Arrays.sort() or natural sorting

Natural sorting is done in three steps. Firstly, toCharArray() method is applied to the input string for creating a character array of the input string. Now, Arrays.sort(char c[]) method is used to sort the character array. Now string class constructor is used for creating a sorted string from the character array.

Example #1
import java.util.Arrays; public class Sortingexample3 < public static String sortString( String initialstringused) < char sameArray[] = initialstringused.toCharArray(); System.out.println( " Mixed kinda character string used \n " ); Arrays.sort( sameArray); System.out.println( " We use character string here \n " ); return new String(sameArray); >public static void main(String[] args) < String initialstringused = " \n Choley Bhature is loved by Rahul \n "; String stringwegetinreturn = sortString( initialstringused ); System.out.println( "Input String : " + initialstringused ); System.out.println("Output String : " + stringwegetinreturn ); >>

output 3

Example #2
import java.util.Arrays; public class Sortingexample4 < public static void main(String args[]) < String[] favouritefood = ; System.out.print(" \n Actual food list entered: \n " ); System.out.println(Arrays.toString(favouritefood)); System.out.print(" \n Rahul favourite foods are: \n " ); Arrays.sort(favouritefood); System.out.println(Arrays.toString(favouritefood)); > >

output 4

Conclusion

On the basis of the above article, we understood the sort string array in Java. Sort String Array has two methods and both the methods are explained in the article using multiple examples. The examples will help the beginners in understanding the implementation of Sort String Array in a Java code to get the required results.

This is a guide to Sort String Array in Java. Here we discuss the Sorting String Array in Java using various methods, explained with examples. You may also have a look at the following articles to learn more –

500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access

Читайте также:  Docx python count pages

1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access

1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access

3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access

All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access

Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access

Источник

Java Sort String Array Example

Java String array sort example shows how to sort string array in Java using Collections class and custom comparator in descending and ascending orders.

How to sort String array in Java?

There are several methods using which you can sort an array of strings.

1) Sort string array using the Arrays class

A string array can be sorted using the sort method of the Arrays class.

This method sorts an array using the natural ordering of the array elements in ascending order.

[Accenture, Aztec, Browser, CAke, PlayStation, Playhouse, Raphael, Yokohama, Zintec, ak56, boB, cEntury, nIntendo, roB, xBox, zOo]

2) Using the Collections class

You can also use the sort method of Collections class along with the asList method to sort an array.

This method sorts the list in ascending order according to the natural order of its elements.

Note: The sort method of the Collections class accepts a List as an argument. To sort an array of strings, you first need to convert array to list using the asList method of the Arrays class.

[Accenture, Aztec, Browser, CAke, PlayStation, Playhouse, Raphael, Yokohama, Zintec, ak56, boB, cEntury, nIntendo, roB, xBox, zOo]

Please note that the asList method provides an abstract list view on the top of the original array. Hence, sorting a list will also modify the underlying original array.

How to sort array in descending order?

By default, the sort method of the Arrays and Collections class sorts an array in ascending order. However, you can use the reverseOrder method of the Collections class to sort array in descending order.

This method returns a comparator that uses the reverse of the natural ordering of the collection elements (descending order for string elements).

You can also use the sort method of the Collections class as given below.

[zOo, xBox, roB, nIntendo, cEntury, boB, ak56, Zintec, Yokohama, Raphael, Playhouse, PlayStation, CAke, Browser, Aztec, Accenture]

How to sort using custom comparator?

As you may have noticed from the output that when we sort an array using the sort method, it outputs “PlayStation” before “Playhouse” and “Zintec” before “ak56” string values.

That is because the sort method sorts string values according to the ASCII values. ASCII value of the capital letter “Z” (90) is less than the ASCII value of the small letter “a” (97) so “Zintec” comes before “ak56” value. What if you want to sort an array of string values regardless of the case of the values? A custom comparator can be used as given below.

Источник

Оцените статью