简体   繁体   中英

Comparing strings by their alphabetical order

String s1 = "Project";
String s2 = "Sunject";

I want to compare the two above string by their alphabetic order (which in this case "Project" then "Sunject" as "P" comes before "S"). Does anyone know how to do that in Java?

String.compareTo might or might not be what you need.

Take a look at this link if you need localized ordering of strings.

Take a look at the String.compareTo method.

s1.compareTo(s2)

From the javadocs:

The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.

String a = "..."; 
String b = "...";  

int compare = a.compareTo(b);  

if (compare < 0) {  
    //a is smaller
}
else if (compare > 0) {
    //a is larger 
}
else {  
    //a is equal to b
} 

You can call either string's compareTo method (java.lang.String.compareTo). This feature is well documented on the java documentation site .

Here is a short program that demonstrates it:

class StringCompareExample {
    public static void main(String args[]){
        String s1 = "Project"; String s2 = "Sunject";
        verboseCompare(s1, s2);
        verboseCompare(s2, s1);
        verboseCompare(s1, s1);
    }

    public static void verboseCompare(String s1, String s2){
        System.out.println("Comparing \"" + s1 + "\" to \"" + s2 + "\"...");

        int comparisonResult = s1.compareTo(s2);
        System.out.println("The result of the comparison was " + comparisonResult);

        System.out.print("This means that \"" + s1 + "\" ");
        if(comparisonResult < 0){
            System.out.println("lexicographically precedes \"" + s2 + "\".");
        }else if(comparisonResult > 0){
            System.out.println("lexicographically follows \"" + s2 + "\".");
        }else{
            System.out.println("equals \"" + s2 + "\".");
        }
        System.out.println();
    }
}

Here is a live demonstration that shows it works: http://ideone.com/Drikp3

For alphabetical order following nationalization, use Collator .

//Get the Collator for US English and set its strength to PRIMARY
Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
if( usCollator.compare("abc", "ABC") == 0 ) {
    System.out.println("Strings are equivalent");
}

For a list of supported locales, see JDK 8 and JRE 8 Supported Locales .

import java.io.*;
import java.util.*;
public class CandidateCode {
    public static void main(String args[] ) throws Exception {
       Scanner sc = new Scanner(System.in);
           int n =Integer.parseInt(sc.nextLine());
           String arr[] = new String[n];
        for (int i = 0; i < arr.length; i++) {
                arr[i] = sc.nextLine();
                }


         for(int i = 0; i <arr.length; ++i) {
            for (int j = i + 1; j <arr.length; ++j) {
                if (arr[i].compareTo(arr[j]) > 0) {
                    String temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        for(int i = 0; i <arr.length; i++) {
            System.out.println(arr[i]);
        }
   }
}

As others have mentioned, you can use String.compareTo , but that will sort all upper-case letters before all lower-case letters, so "Z" will come before "a".

If you just want to sort them in alphabetical order regardless of case (so that "a" comes before "Z"), you can use String.compareToIgnoreCase :

s1.compareToIgnoreCase(s2);

This returns a negative integer if s1 comes before s2 , a positive integer if s2 comes before s1 , and zero if they're equal. Since this method ignores case completely, two strings that differ only by case are considered equal, for example "ABC".compareToIgnoreCase("abc") will return zero.

As others suggested, you can use String.compareTo(String) .

But if you are sorting a list of Strings and you need a Comparator , you don't have to implement it, you can use Comparator.naturalOrder() or Comparator.reverseOrder() .

String s1 = "Project";
String s2 = "Sunject";

//print smaller one using compareTo() function
if(s1.compareTo(s2)<0) System.out.println(s1);
//if s1 is smaller then function returns negative which is less than 0 so s1 
//is smaller
else System.out.println(s2); // else s2 is smaller

//print larger one using compareTo() function
if(s1.compareTo(s2)>0) System.out.println(s1);
//is s1 is larger function will give positive so print s1 else s2 
else System.out.println(s2);

Person.java

import java.util.Objects;
public class Person implements Comparable {
String firstName;
String lastName;
Integer age;
Integer DOBYear;

public Person(String firstName, String lastName, Integer age, Integer DOBYear) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.DOBYear = DOBYear;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public Integer getAge() {
    return age;
}

public void setAge(Integer age) {
    this.age = age;
}

public Integer getDOBYear() {
    return DOBYear;
}

public void setDOBYear(Integer DOBYear) {
    this.DOBYear = DOBYear;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Person person = (Person) o;
    return Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName) && Objects.equals(age, person.age) && Objects.equals(DOBYear, person.DOBYear);
}

@Override
public int hashCode() {
    return Objects.hash(firstName, lastName, age, DOBYear);
}

@Override
public int compareTo(Object o) {
    Person p = (Person) o;
    return p.getAge() > this.getAge() ? -1: p.getAge() == this.getAge() ? 0 : 1;
}

@Override
public String toString() {
    return "Person{" +
            "firstName='" + firstName + '\'' +
            ", lastName='" + lastName + '\'' +
            ", age=" + age +
            ", DOBYear=" + DOBYear +
            '}';
}

}

PersonNameComparator

import java.util.Comparator;

public class PersonNameComparator implements Comparator<Person> {


@Override
public int compare(Person o1, Person o2) {
    return o1.getFirstName().compareTo(o2.getFirstName());
}

}

PersonTest.java#

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class PersonTest {
public static void main(String args[]){

    System.out.println("Hello World");
    Person p1 = new Person("Umesh","Bhutada",31,1991);
    Person p2 = new Person("Deepali","Baheti",29,1992);
    Person p3 = new Person("Romeet","Zanwar",5,2017);

    ArrayList<Person> arr1 = new ArrayList<Person>( Arrays.asList(p1,p2,p3));
    Collections.sort(arr1);

    arr1.forEach(person -> {System.out.println( person);});

    System.out.println("End of World");

    System.out.println("test 2");

    Collections.sort(arr1,new PersonNameComparator());
    arr1.forEach(person -> {System.out.println( person);});

}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM