StringLengthComparator.java

/***************************************************************************
   Copyright 2008 Emily Estes

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
***************************************************************************/
package net.metanotion.util;


import java.io.Serializable;
import java.util.Comparator;

/** A comparator for Strings that sorts by length FIRST.
	This comparator will sort all strings of length N to be prior to strings of length N + 1.
	If two strings are of equal length, normal string comparison rules apply(see String.compareTo(String)).
	Note: This class implements Serializable because FindBugs noted that stateless Comparator's by convention
	should.
*/
public final class StringLengthComparator implements Comparator<String>, Serializable {
	@Override public int compare(String o1, String o2) {
		if(((o1 == null) || (o1.length() == 0)) && ((o2 == null) || (o2.length() == 0))) { return 0; }
		if(o1 == null) { return 1; }
		if(o2 == null) { return -1; }
		if(o1.length() == o2.length()) { return o1.compareTo(o2); }
		if(o1.length() > o2.length()) { return -1; }
		return 1;
	}
}