Skip to content

Instantly share code, notes, and snippets.

@JohnZavyn
Last active May 4, 2017 14:31
Show Gist options
  • Save JohnZavyn/1b5265b7eee0f10d9564bc223ceb64ee to your computer and use it in GitHub Desktop.
Save JohnZavyn/1b5265b7eee0f10d9564bc223ceb64ee to your computer and use it in GitHub Desktop.
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