I am implementing the compareto ()
method for a simple class like it ( To be enabled) to use .sort ()
and other platforms to be used by Java platforms):
implements the public category metadata Comparable & Lt; Metadata & gt; {Name of the private string; Private string value; // Basic Constructors and Accessories here Imagine // Unrelevant part omitted}
I want natural order for these items: 1) Sort by name and 2) Sorted by value if the name is the same; Both comparisons should be case-insensitive. For both areas zero values are completely acceptable, so compare
should not be broken in these cases.
The solution that occurs in spring is on the pattern below (I am using "guard clause" here while others prefer a return point, but it is next to the point):
// primarily by name, depending on the value; Null-safe; Case insensitive public int comparison (metadata other) {if (this.name == faucet and other names! = Null) {return -1; } And if (this.name! = Null & amp; other .name == faucet) {return1; } And if (this.name! = Null & other name! = Null) {int results = this.name.compareToIgnoreCase (other name); If (result! = 0) {return result; }} If (this.value == faucet) {return.value == null? 0: -1; } If (other.value == faucet) {return1; } Return this return.value.compareToIgnoreCase (other.value); }
This works, but I am not completely happy with this code. This is definitely not the lot premises, but it is quite clear and tedious.
The question is, how will you do this short dictionary (while maintaining the functionality)? If they help, feel free to refer to Java standard libraries or Apache Commons, right of Eddie: the only option would be to make this (a small one)
Edit 1 -3 can apply to my own "NullSafeStringComparator", and to apply for comparison of both areas? ;
About the accepted answer I returned this question back in 2009, definitely at Java 1.6, and at that time accepted my favorites The answer was: I have never been round to change (2017) so far.
There are also - one of the 2009 Apache Commons Collections is one and 2013 is a Guo, both have posted - I have some time on time.
Now I have made clear the accepted answer. It should definitely be preferred, if Java 8, and these days Java 8 should be available for almost all projects.
Java 8 :
Private Static comparator & lt; String & gt; NullSafeStringComparator = Comparator NullsFirst (String :: Compare Anwerkos); Private static comparative & lt; Metadata & gt; MetadataComparator = Comparative .comparing (metadata :: getName, nullSafeStringComparator). ThenComparing (Metadata :: getValue, nullSafeStringComparator); To compare Public Int (Metadata is that) {Return Metadata Komparator.compare (this, that); }
Comments
Post a Comment