Академический Документы
Профессиональный Документы
Культура Документы
HowdoIsortacollectionorarrayofstrings?WebTutorialsavajava.com
Search Tutorials:
Go
Web Tutorials ::
General Java
Tutorial Categories:
::
1. Ajax (1)
2. Ant (16)
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse
4. Bioinformatics (10)
3.3.0)
Java
strings, you can sort the strings via a call to Arrays.sort(), such as:
Arrays.sort(stringArray);
If you require the Strings to be sorted without regards to case, you'll need a
second argument, a Comparator, for Arrays.sort(). Such a comparator has already
been written for us and can be accessed as a static on the String class named
CASE_INSENSITIVE_ORDER.
Arrays.sort(stringArray,String.CASE_INSENSITIVE_ORDER);
Similarly if you have a collection of strings, you can sort the collection via calls
to:
Collection.sort(stringCollection);
and
Collection.sort(stringCollection,String.CASE_INSENSITIVE_ORDER);
http://www.avajava.com/tutorials/lessons/howdoisortacollectionorarrayofstrings.html
1/3
12/16/2016
HowdoIsortacollectionorarrayofstrings?WebTutorialsavajava.com
StringSortExample.java
packageexample;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.Collections;
importjava.util.List;
publicclassStringSortExample{
publicstaticvoidmain(String[]args)throwsException{
String[]strArray={"Carol","bob","Alice"};
displayArray(strArray);
Arrays.sort(strArray);
displayArray(strArray);
Arrays.sort(strArray,String.CASE_INSENSITIVE_ORDER);
displayArray(strArray);
System.out.println("");
List<String>strList=newArrayList<String>();
strList.add("larry");
strList.add("Moe");
strList.add("Curly");
displayList(strList);
Collections.sort(strList);
displayList(strList);
Collections.sort(strList,String.CASE_INSENSITIVE_ORDER);
displayList(strList);
publicstaticvoiddisplayArray(String[]array){
for(Stringstr:array){
System.out.print(str+"");
System.out.println();
publicstaticvoiddisplayList(List<String>list){
for(Stringstr:list){
System.out.print(str+"");
System.out.println();
The console output is shown here. Notice after the first sort of the array and the
first sort of the collection, the results have been alphabetized but case matters
(uppercase words come before lowercase words). Notice that after the second
sort of the array and the second sort of the collections, the results have been
alphabetized without regards to case.
http://www.avajava.com/tutorials/lessons/howdoisortacollectionorarrayofstrings.html
2/3
12/16/2016
HowdoIsortacollectionorarrayofstrings?WebTutorialsavajava.com
Console Output
CarolbobAlice
AliceCarolbob
AlicebobCarol
larryMoeCurly
CurlyMoelarry
CurlylarryMoe
If you require other types of sorting, you can write your own Comparator, where
you define your sorting logic in the compare() method of the Comparator
interface.
Web Tutorials ::
General Java
::
http://www.avajava.com/tutorials/lessons/howdoisortacollectionorarrayofstrings.html
3/3