Last active
May 4, 2017 14:31
-
-
Save JohnZavyn/1b5265b7eee0f10d9564bc223ceb64ee to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.threeleaf.util; | |
import java.util.Comparator; | |
/** | |
* A {@link Comparator} that allows any two objects to be sorted based on {@link Object#toString()}. | |
* This works best when the object's toString returns something meaningful, but can still be | |
* useful in cases where a object one has not control over needs to be placed in a sorted | |
* collection. | |
* <p> | |
* Usage: | |
* <pre>{@code | |
* final Set<Object> set = new TreeSet<>(new ToStringComparator()); | |
* // en_US | |
* set.add(Locale.US); | |
* // en_CA | |
* set.add(Locale.CANADA); | |
* // en | |
* set.add(Locale.ENGLISH); | |
* }</pre> | |
* produces the sorted set: {@code [ENGLISH, CANADA, US]} instead of an exception. | |
*/ | |
@SuppressWarnings("WeakerAccess") | |
public class ToStringComparator implements Comparator<Object> | |
{ | |
/** Instantiate a new {@link ToStringComparator}. */ | |
public ToStringComparator() | |
{ | |
super(); | |
} | |
/** {@inheritDoc}. */ | |
public int compare(final Object object1, final Object object2) | |
{ | |
return object1.toString().compareTo(object2.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment