Java compare string int

Java compare string int

A comparator, which compares strings by their length, would be implemented as follows:

public class StringLengthComparator implements ComparatorString> < @Override public int compare(String o1, String o2) < if (o1.length() < o2.length()) < return -1; > else if (o1.length() == o2.length()) < return 0; > else < return 1; > > >Code language: Java (java)

Again we can compress the code to a single line using the ternary operator:

@Override public int compare(String o1, String o2) < return o1.length() < o2.length() ? -1 : (o1.length() == o2.length() ? 0 : 1); >Code language: Java (java)

We can use the StringLengthComparator as follows:

public class NameSortByLengthExample < public static void main(String[] args) < String[] names = "Mary", "James", "Patricia", "John", "Jennifer", "Robert">; Arrays.sort(names, new StringLengthComparator()); System.out.println(Arrays.toString(names)); > >Code language: Java (java)

The names are no longer sorted alphabetically, but by their length in ascending order:

[Mary, John, James, Robert, Patricia, Jennifer]Code language: plaintext (plaintext)

How to Create a Comparator?

Up to Java 7, you could create a comparator – as shown in the example above – only by implementing the Comparator interface.

Since Java 8, you can also notate a comparator as a Lambda expression or – quite conveniently, as you will see in a moment – using the methods Comparator.comparing() , thenComparing() , and reversed() .

Читайте также:  Css обои на телефон

Comparator as a Public Class

Using the example StringLengthComparator , we have already seen the first variant: We write a public class and pass an instance of it to the sorting method:

Arrays.sort(names, new StringLengthComparator());Code language: Java (java)

If we want to sort by string length in several places, we can also extract a constant:

private static final StringLengthComparator STRING_LENGTH_COMPARATOR = new StringLengthComparator();Code language: Java (java)

Alternatively, we could define a singleton:

public class StringLengthComparator implements ComparatorString> < public static final StringLengthComparator INSTANCE = new StringLengthComparator(); private StringLengthComparator() <> @Override public int compare(String o1, String o2) < return Integer.compare(o1.length(), o2.length()); > >Code language: Java (java)

A public class also gives us the possibility to control the sorting behavior by constructor parameters. For example, we could make the sort order configurable:

public class StringLengthComparator implements ComparatorString> < public static final StringLengthComparator ASC = new StringLengthComparator(true); public static final StringLengthComparator DESC = new StringLengthComparator(false); private final boolean ascending; private StringLengthComparator(boolean ascending) < this.ascending = ascending; > @Override public int compare(String o1, String o2) < int result = Integer.compare(o1.length(), o2.length()); return ascending ? result : -result; > > Code language: Java (java)

We would use this comparator, for example, as follows to sort our list of names in descending order:

Arrays.sort(names, StringLengthComparator.DESC);Code language: Java (java)

A public class thus gives us the greatest possible freedom and flexibility in defining our comparator.

Comparator as an Anonymous Class

If we need a comparator in only one place, we can also define it as an anonymous class.

With the following code, for example, we sort our students by last name:

students.sort(new Comparator() < @Override public int compare(Student o1, Student o2) < return o1.getLastName().compareTo(o2.getLastName()); > >);Code language: Java (java)

Since some last names occur more frequently, we should perhaps sort better by last and first name. We do this by first checking if the last names are the same. If this is the case, we also compare the first names:

students.sort(new Comparator() < @Override public int compare(Student o1, Student o2) < int result = o1.getLastName().compareTo(o2.getLastName()); if (result == 0) < result = o1.getFirstName().compareTo(o2.getFirstName()); >return result; > >);Code language: Java (java)

In both cases, a modern IDE like IntelliJ will tell us that you can do this more elegantly from Java 8 on (and it will ideally also offer us to refactor the code):

Refactoring a Comparator to a Lambda expression

You will find out what the result is in the next section.

Writing a Java Comparator as a Lambda

From Java 8 on, we can use a Lambda instead of the anonymous class. Sorting by last name is then done as follows:

students.sort((o1, o2) -> o1.getLastName().compareTo(o2.getLastName()));Code language: Java (java)

Sorting by last and first name is also made shorter by the Lambda notation:

students.sort((o1, o2) -> < int result = o1.getLastName().compareTo(o2.getLastName()); if (result == 0) < result = o1.getFirstName().compareTo(o2.getFirstName()); >return result; >);Code language: Java (java)

Things will get really nice with the method that I will show in the following section. A modern IDE also offers us this step:

Refactoring to a Comparator chain

Java 8: Creating a Comparator With Comparator.comparing()

The most elegant method for constructing a comparator, which is also available since Java 8, is the use of Comparator.comparing() , Comparator.thenComparing() and Comparator.reversed() – as well as their variations for the primitive data types int , long and double .

To sort the students by last name, we can write the following:

students.sort(Comparator.comparing(Student::getLastName));Code language: Java (java)

We simply pass a reference to the method that returns the field to be sorted by.

We sort by last and first names as follows:

students.sort(Comparator.comparing(Student::getLastName) .thenComparing(Student::getFirstName));Code language: Java (java)

This notation makes it very easy for us to also cover the scenario where two students have the same last name and the same first name. To sort them additionally by ID, we just have to add a thenComparingInt() :

students.sort(Comparator.comparing(Student::getLastName) .thenComparing(Student::getFirstName) .thenComparingInt(Student::getId));Code language: Java (java)

Comparator.comparing() and the comparator chains we can build with it make the code shorter and more concise.

Comparable vs. Comparator – Summary

In the course of the article, we learned about the interfaces java.lang.Comparable and java.util.Comparator . Let me summarize the differences in a few sentences:

By implementing the Comparable.compareTo() method, we define the natural order of objects of a class, i.e., the order by which the objects of the class are sorted by default, e.g., by Arrays.sort(arrayOfObjects) or Collections.sort(listOfObjects) .

Using a Comparator , we can sort objects in an order other than their natural order. And we can sort objects that do not implement the Comparable interface, i.e., that do not have a natural order.

Since Java 8, comparators can be defined very elegantly, as for example in students.sort(Comparator.comparing(Student::getLastName) .

If you liked the article, please share it using one of the share buttons at the end or leave me a comment.

Do you want to be informed when new articles are published on HappyCoders.eu? Then click here to sign up for the HappyCoders.eu newsletter.

Источник

How to compare String and int?

send pies

posted 14 years ago

  • Report post to moderator
  • How do we write a code that does this:

    a) if the user key-in any number from 0 to 100, it will loop and perform some task.
    b) if the user key-in any number less than 0 or more than 100, it will prompt the user to re-enter the correct number.
    c) if the user type-in «quit», it will exit the loop and terminate the program.

    I know how to check the numbers.

    But how do I use the same ‘input’ variable as a String to check if it is equal to «quit» or not?

    The ‘input’ variable can only be an ‘int’ or a ‘String’, right? So, how do we use the same variable to compare 2 different things?

    Or do we need to use a different loop and ask the user «Do you want to continue, y or n? after every loop?

    Is it possible to keep looping until the user key-in «quit», without asking the same question over and over again?

    Bartender

    send pies

    posted 14 years ago

  • Report post to moderator
  • Is it possible to keep looping until the user key-in «quit», without asking the same question over and over again?

    The ‘input’ variable can only be an ‘int’ or a ‘String’, right? So, how do we use the same variable to compare 2 different things?

    Keep the input variable a String and parse it into an int.But be advised, since you will be using «quit», the parsing will throw an exception.You need to take care of this.

    send pies

    posted 14 years ago

  • Report post to moderator
  • First the input variable has to be either an int or a String. In Java a reference can only be a single type, and it cannot change its type. So what you can do is:

    Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. — Laurence J. Peter

    send pies

    posted 14 years ago

  • Report post to moderator
  • Thank you for your replies.
    I’ve changed my code and use Integer.parseInt() but the code is still incorrect. I don’t know how to get rid of the method that asks «do you want to continue?» after every line. How do I make it loop automatically?

    Furthermore, when I press «N», it will print «end» many times. I think it’s repeating the entire loop again. I can’t use the ‘break’; statement, it gives me an error which says «the break is outside the loop».

    Any idea how to rectify it?

    Marshal

    send pies

    posted 14 years ago

  • Report post to moderator
  • Somebody else had a rather similar problem back in the Spring; maybe her thread will help: here.

    But it is particularly awkward trying to check whether a String is a number or «quit» in the same statement.

    send pies

    posted 14 years ago

  • Report post to moderator
  • Originally posted by Campbell Ritchie:
    Somebody else had a rather similar problem back in the Spring; maybe her thread will help: here.

    But it is particularly awkward trying to check whether a String is a number or «quit» in the same statement.

    Thanks for the link to the thread. It was very helpful. There are many while loops in her method and the method gets quite big. I was thinking of a more OO approach. I want to make my methods smaller.

    The method for checking invalid number is working fine. But when it comes to checking for Y or N — it is giving me a «NullPointerException» error. Any idea why? I think, I know, it’s because it’s asking for a number input again and I don’t have it. But how do I bypass that?

    It’s a simple program but I just can’t figure it out yet. Need some pointers in the right direction, please.
    Thank you!

    Источник

    Java compare string int

    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 String compareTo() Method

    The compareTo() method compares two strings lexicographically.

    The comparison is based on the Unicode value of each character in the strings.

    The method returns 0 if the string is equal to the other string. A value less than 0 is returned if the string is less than the other string (less characters) and a value greater than 0 if the string is greater than the other string (more characters).

    Tip: Use compareToIgnoreCase() to compare two strings lexicographyically, ignoring lower case and upper case differences.

    Tip: Use the equals() method to compare two strings without consideration of Unicode values.

    Syntax

    public int compareTo(String string2) public int compareTo(Object object) 

    Parameter Values

    Parameter Description
    string2 A String , representing the other string to be compared
    object An Object , representing an object to be compared

    Technical Details

    Returns: An int value: 0 if the string is equal to the other string.
    < 0 if the string is lexicographically less than the other string
    > 0 if the string is lexicographically greater than the other string (more characters)

    ❮ String Methods

    Источник

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