Java Comparator

Does any one know of some kind of Comparator factory in Java, with a

public Comparator getComparatorForClass(Class clazz) {}

It would return Comparators for stuff like String, Double, Integer but would have a

public void addComparatorForClass(Class clazz, Comparator comparator) {}

For arbitrary types.


Asked by: Edward391 | Posted: 28-01-2022






Answer 1

Instead of:

factory.getComparatorForClass(x.getClass()).compare(x, y)

you could simply implement Comparable and write:

x.compareTo(y)

String, the primitive wrappers, and standard collections already implement Comparable.

Answered by: Lenny154 | Posted: 01-03-2022



Answer 2

Use CompareToBuilder from Commons Lang.

Assists in implementing Comparable.compareTo(Object) methods.

To use this class write code as follows:

public class MyClass {
  String field1;
  int field2;
  boolean field3;

  ...

  public int compareTo(Object o) {
    MyClass myClass = (MyClass) o;
    return new CompareToBuilder()
      .appendSuper(super.compareTo(o)
      .append(this.field1, myClass.field1)
      .append(this.field2, myClass.field2)
      .append(this.field3, myClass.field3)
      .toComparison();
  }
}

Answered by: Aldus532 | Posted: 01-03-2022



Answer 3

I'm not aware of anything like that off the top of my head. If you really need something like this, it shouldn't be too difficult to implement one yourself.

However, could you elaborate on why you need something like this? There typically should not be a "default" comparator for classes. If the class has some sort of natural ordering, you really ought to have it implement java.lang.Comparable, and implement Comparable#compareTo(Object) : int instead.

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html

Answered by: Kevin737 | Posted: 01-03-2022



Answer 4

Comparator are need to be extend.. this is based on the reusable code implementation.. in these method you can have a custom comparison of data.. the implementation is just simple.. just implement the Comparator interface.. override its compareto method and place the comparison code.. and return which you think is greater in terms of values..

Answered by: Lydia195 | Posted: 01-03-2022



Answer 5

Default comparator is not exist in Java. However, if you are coding with, for example, a customized searcher, which intends to use comparator rather than the compareTo() method of derived type of Comparable class, you may write a static inner comparator class as the default comparator, simply implementing the compare() method by calling the compareTo().

Example:

class Searcher> { private Comparator comparator;

Searcher(Comparator<T> comparator) {
    this.comparator = comparator;
}

Searcher() {
    this(new DefaultComparator<T>());
}

int search(...) {
    ...
}

private static class DefaultComparator<E extends Comparable<E>> 
        implements Comparator<E> {
    public int compare(E o1, E o2) {
        return o1.compareTo(o2);
    }
}

Answered by: Lucas988 | Posted: 01-03-2022



Similar questions

Why Java does not support Equality comparison on the Lines of Comparator?

Java provides way to define comparison of object outside scope Object using Comparator. Now my questions is why java does not allow do same for equals() and hashcode(). Now each collection contains() method can easily use this external equality provider to check objects are equal.


java - Custom comparison using Comparator

I have a variable which can take on three possible values ( or status ) : Available, Partial, Not Available. Now, I have a list of these statuses. My job is to to summarize the entire result onto one status. I mean that even if one of the status in the list is Not Available, then the overall status becomes Not Available. If all the statuses in the list are Avail...


java - Comparator to get the maximum value in Linked List with exclude the first element of the Linked List from the comparison

I am trying to extract the maximum value from the LinkedList,but with one condition that I want the first element of the LinkedList being out of the comparison and without relying on the values stored inside the first element. Can I use the index of the LinkedList or whatever to exclude the first element through the comparison. This is what I have done but I do not know how implement this condition: import...


java - Equality comparison -- any saner way?

How do I implement this equality comparison is a sane java way? boolean x = (a == b) || (a.equals(b)) I want to make sure the content of both objects is equal but null is also ok, i.e. both can be null and are thus equal. Update: just to be clear, I have to implement this comparison several times and don't want to copy&amp;paste this stuff every time, especially with lenghty ob...


floating point - Java double comparison epsilon

I wrote a class that tests for equality, less than, and greater than with two doubles in Java. My general case is comparing price that can have an accuracy of a half cent. 59.005 compared to 59.395. Is the epsilon I chose adequate for those cases? private final static double EPSILON = 0.00001; /** * Returns true if two doubles are considered equal. Tests if the absolute * difference between two doub...


java - JavaBeans Comparison

Does anyone know about a free open source library (utility class) which allows you to compare two instances of one Java bean and return a list/array of properties which values are different in those two instances? Please post a small sample. Cheers Tomas


java - String Comparison : individual comparison Vs appended string comparison

I have six string variables say str11, str12, str13, str21, str21 and str23. I need to compare combination of these variables. The combinations I have to check is str11 -- str12 -- str13 as one group and str21 -- str22 -- str23 as other group. I have to compare these two groups. Now I'm in confusion which method should I use for comparison? Can I append strings of same group and compare, whi...


Java: Double Value Comparison

Do we need to be careful when comparing a double value against zero? if ( someAmount &lt;= 0){ ..... }


Java Embedded Databases Comparison

Closed. This question does not meet Stack Overflow guid...


java - If statement with String comparison fails

This question already has answers here:


cocoa - MVC and Java in comparison with more strict MVC languages

I've been told Java is not the greatest pick to follow an MVC architecture. I believe I've seen some Java framework solutions to ease this roadbump. However, I a bit confused on why this is. More specifically, why Java's attempt at MVC is often mocked as a "wannabe" approach. I come from a ObjC background (w/ Cocoa of course) and would love to hear from the seasoned programmers about why MVC with Java is said to fall short...


java - Efficient comparison of 100.000 vectors

I save 100.000 Vectors of in a database. Each vector has a dimension 60. (int vector[60]) Then I take one and want present vectors to the user in order of decreasing similarity to the chosen one. I use Tanimoto Classifier to compare 2 vectors:


java - SQL Server JBDC Driver comparison

Currently we use jtds for connecting to our SQL Server databases. I've always taken it for granted that we use it due to performance and reliability reasons, however, it's usage pre-dates my employment. All of that being said, we are now playing with the idea of moving to SQL Server 2008, which jtds has limited support for. Initial tests seem to indicate ...






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top