- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort String Array alphabetically by the initial character only in Java
Here, we are sorting string array alphabetically by the initial character i.e. ‘J’ for ‘John’ will come after ‘Chris’ since the first character of ‘Chris’ is ‘C’.
Let us first create a String array:
String[] strArr = { "PQRS", "AB", "RSTUVW", "RST", "U", "UVWXY", "OUJBG" };
Now, sort the string array based on the first character:
Arrays.sort(strArr, (str1, str2) -> str1.charAt(0) - str2.charAt(0));
The following is an example to sort String Array alphabetically by the initial character only:
Example
import java.util.Arrays; public class Demo { public static void main(String[] args) { String[] strArr = { "PQRS", "AB", "RSTUVW", "RST", "U", "UVWXY", "OUJBG" }; System.out.println("Sorting array strings = "); Arrays.sort(strArr, (str1, str2) -> str1.charAt(0) - str2.charAt(0)); Arrays.asList(strArr).forEach(System.out::println); } }
Output
Sorting array strings = AB OUJBG PQRS RSTUVW RST U UVWXY
- Related Articles
- How to Sort a String in Java alphabetically in Java?
- How to sort the letters in a string alphabetically in Python?
- Python – Sort String list by K character frequency
- Convert the string into palindrome string by changing only one character in C++
- MySQL query to sort by certain last string character?
- Creating String Object from Character Array in Java
- Difference between String and Character array in Java.
- How to sort a String array in Java?
- Sort by character length in MySQL
- Sort array of objects by string property value in JavaScript
- Java program to convert a character array to string
- Java Program to create Character Array from String Objects
- Sort array of objects by string property value - JavaScript
- How to cut only the first character in MySQL string?
- Sort only numbers from alphanumeric string in MySQL?

Advertisements