Array sorted java string

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.

Источник

Array sorted 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

Источник

Сортировка списка строк в Java

В этом посте мы обсудим, как отсортировать список строк в лексикографическом порядке в Java.

1. Использование Collections.sort() метод

Простое решение для на месте отсортировать список строк в лексикографическом порядке с помощью Collections.sort() метод. Он принимает изменяемый список, размер которого не обязательно должен изменяться.

результат:

[Amazon, Apple, Facebook, Google, Netflix]

The Collections.sort() метод необязательно принимает компаратор, чтобы обеспечить точный контроль над порядком сортировки. Чтобы сделать сравнение между двумя строками нечувствительными к регистру, вы можете использовать String.CASE_INSENSITIVE_ORDER comparator.

результат:

[Amazon, APPLE, Facebook, GOOGLE, Netflix]

2. Использование List.sort() метод

Другой альтернативой сортировке списка строк на месте является метод List.sort() метод, добавленный в спецификацию JDK 1.8. Collections.sort() метод представляет собой оболочку над List.sort() метод. Следовательно, приведенный выше код эквивалентен:

результат:

[Amazon, Apple, Facebook, Google, Netflix]

Вы можете использовать String.CASE_INSENSITIVE_ORDER компаратор, чтобы операция сортировки сравнивала строки, игнорируя их порядок.

результат:

[Amazon, APPLE, Facebook, GOOGLE, Netflix]

3. Использование Stream.sorted() метод

Чтобы создать отсортированную копию списка, вы можете использовать Java 8 Stream. Идея состоит в том, чтобы создать последовательный поток по элементам в списке, отсортировать поток с помощью sorted() и соберите все отсортированные элементы в новый список. Это показано ниже:

Источник

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.

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

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

Источник

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