Created
October 22, 2013 13:02
-
-
Save zhangll/7100340 to your computer and use it in GitHub Desktop.
Compare Special String Not Valid!
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 snippet; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.util.List; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
import org.junit.Test; | |
public class Compare { | |
@Test | |
public void TestCompareString() { | |
@SuppressWarnings("serial") | |
List<String> ids = new ArrayList<String>(){{ | |
add("22"); | |
add("2B"); | |
add("2A"); | |
add("2"); | |
add("33"); | |
}}; | |
System.out.println("---before sort---"); | |
for (String string : ids) { System.out.print(string + "\t"); } | |
final Pattern pattern = Pattern.compile("^([0-9]*)([a-zA-Z]*)$"); | |
//sort | |
Collections.sort(ids, new Comparator<String>() { | |
@Override | |
public int compare(String s1, String s2) { | |
if(s1 == s2) { | |
return 0; | |
} | |
if(s1 == null && s2 != null) { | |
return -1; | |
} | |
if(s1 != null && s2 == null) { | |
return 1; | |
} | |
Matcher matcher1 = pattern.matcher(s1); | |
Matcher matcher2 = pattern.matcher(s2); | |
String str1_num = null; | |
String str1_char = null; | |
if (matcher1.find()) { | |
str1_num = matcher1.group(1); | |
str1_char = matcher1.group(2); | |
} | |
String str2_num = null; | |
String str2_char = null; | |
if (matcher2.find()) { | |
str2_num = matcher2.group(1); | |
str2_char = matcher2.group(2); | |
} | |
//compare number first,then char | |
int r = str1_num.compareTo(str2_num); | |
return r == 0 ? str1_char.compareTo(str2_char) : r; | |
} | |
}); | |
//print result | |
System.out.println("\r---after sort---"); | |
for (String string : ids) { System.out.print(string + "\t");} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment