How can I compare two Strings using comparable interface?

java string comparator
how to write a compareto method in java
java compareto implementation
compareto java return values
java string compare
java compare strings alphabetically
compareto java int
override compareto java

The code provided below is used for sorting int values. What I want to do now, is to sort them into Strings.

public class Comparable5 {

    public static void main(String[] args) {
        TreeSet ts = new TreeSet();
        ts.add(new Student1(2, "Thilan"));
        ts.add(new Student1(1, "Kamal"));
        ts.add(new Student1(3, "Nimal"));

        System.out.println(ts);
    }
}

class Student1 implements Comparable<Student> {

    int id;
    String name;

    public Student1(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return this.id + ":" + this.name;
    }

    @Override
    public int compareTo(Student o) {
        if (o.name.equals(this.name)) {
            return -1;
        } else if (o.name.equals(this.name)) {
            return +1;
        } else {
            return 0;
        }
    }
}

I'm trying to ascend names using Comparable interface. I have used equals() method, however I was unable to get ascending order. I tried comparing different objects using comparable interface. I have used a constructor that has two parameters.

I have already done sorting IDs, but was unable to sort them by names(String). How can I sort Strings using compareTo() method in Comparable interface?

Here:

 @Override
 public int compareTo(Student o) {
   return this.name.compareTo(o.name);
 }

is "all" you need.

But of course, what you really need to understand is the idea behind these compareTo() methods. Your code implies that you don't. You return 0 when the two things are equal. Only then!

In your case, you can delegate all that work to the compareTo() implementation of the String class (which will use lexicographical sorting to compute the result), see here for example.

But as said: your real problem is the lack of understand why you are doing things! Beyond that: please note that references can be null. My example is just that: an example. In real world code, you would have to do much more, like thinking which values could be null, and how your code should react to that, in order to avoid exceptions flying around.

How do I compare strings in Java?, What happens when you compare two string objects with the == operator? Using Comparable interface, we can sort the elements of: String objects; Wrapper class objects, for example Integer, Long etc; User defined custom objects; 1.1. compareTo() method. For any class to support natural ordering, it should implement the Comparable interface and override it’s compareTo() method.

Strings are comparable (i.e. it implements Comparable<String>), so you can call the String's compareTo() method.

@Override
public int compareTo(Student o) {
    return this.name.compareTo(o.name);
}

If you want to reverse the order, swap the this and o.

5 ways to Compare String Objects in Java, What is difference between == equals () and compareTo () method? Comparable interface is mainly used to sort the arrays (or lists) of custom objects. Lists (and arrays) of objects that implement Comparable interface can be sorted automatically by Collections.sort (and Arrays.sort). Before we see how to sort an objects of custom objects,

Note that with this

class Student1 implements Comparable<Student>

you will probably run into problems. Looking at the javadoc for Comparable, you

must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y

and

that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.

This means that you also need to make sure that Student implements Comparable<Student1> with a proper comparison.

It does not feel like this is a road you want to go down.

Java String Compare, checks if two objects are the same or not and returns a boolean. These examples demonstrate the main difference between Comparable and Comparator. Use Comparable when there is a single, default comparison for your object. Use Comparatorwhen you need to work around an existing compareTo(), or when you need to use specific logic in a more flexible way.

 @Override
 public int compareTo(Student student) {
   return this.name.compareTo(student.name);
 }

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

compareTo() vs. equals(), Usually when implementing the Comparable interface, you will just aggregate the results of using other Comparable members of the class. Also in your code, do not try to compare Strings using '=='. Use 'equals' method instead. '==' only compare string references while equals semantically compares two strings. Comparable interface - how to compare int type? comparison of two Second objects. You can either use it when you let your Second class implement the Comparable

How to use the Comparable CompareTo on Strings in Java, String compareTo() Method in Java with Example​​ compareTo() is used for comparing two strings lexicographically. Each character of both strings are converted into a Unicode value. However, if both the strings are equal, then this method returns 0 else it only result either negative or positive value. The Comparator interface defines two methods: compare ( ) and equals ( ). The compare ( ) method, shown here, compares two elements for order − The compare Method. int compare (Object obj1, Object obj2) obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It returns a positive value if obj1 is

String compareTo() Method in Java with Example, Java String compareTo() method is used to compare two strings, this method is case sensitive, lets understand compareTo() with the help of examples. Using Comparable Interface. A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface to compare its instances. Consider a Movie class that has members like, rating, name, year. Suppose we wish to sort a list of Movies based on year of release. We can implement the Comparable interface with the Movie class, and we override the method compareTo() of Comparable interface.

Java String compareTo() Method with examples, In java Comparable interface compares values and returns an int, these int values may be less than, equal, or greater than. The java compare two string is based  Note: String class and Wrapper classes implement the Comparable interface by default. So if you store the objects of string or wrapper classes in a list, set or map, it will be Comparable by default. Java Comparable Example. Let's see the example of the Comparable interface that sorts the list elements on the basis of age.

Comments
  • Best thing to do is to start by reading the class java doc
  • Why don't you do o.name.compareTo ?
  • Thanks for the help.i have figure out the way.we can.yes we can use override compareTo().
  • Don't forget to accept an answer below using the checkmark next to a post
  • Although this code might (or might not) solve the problem, a good answer always requires an explanation on how this code helps.