方法一:
package abc; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; public class TestSort { /* 请将A:1,C:8,D:1,B:3,B:1,F:1,E:5,Z:0,C:1...这样的一组数据进行按“:”的前半部分和后半部分排序 */ public static void main(String[] args) { List<Str> list = new ArrayList<Str>(); StringBuffer b = new StringBuffer(); String a = "A:1,C:8,D:1,B:3,B:1,F:1,E:5,Z:0,C:1"; String[] arr = a.split(","); for (int i = 0; i < arr.length; i++) { Str str = new Str(arr[i].split(":")[0], arr[i].split(":")[1]); list.add(str); } Collections.sort(list); Iterator iterator = list.iterator(); while (iterator.hasNext()) { Str str = (Str)iterator.next(); b.append(str.leftStr + ":" + str.rightStr + ","); } System.out.print("排序后序列是:" + b); }
} class Str implements Comparable { String leftStr; String rightStr; public Str(String leftStr, String rightStr) { this.leftStr = leftStr; this.rightStr = rightStr; } public int compareTo(Object o) { Str str = (Str)o; int rs1 = str.leftStr.compareTo(this.leftStr); int rs2 = str.rightStr.compareTo(this.rightStr); int rs = -1; if (rs1 == rs2) { rs = rs1; } else if (rs1 > 0) { rs = 1; } else if (rs1 < 0) { rs = -1; } else if (rs1 == 0 && rs2 > 0) { rs = 1; } else if (rs1 == 0 && rs2 < 0) { rs = -1; } return rs; } }
方法二:
package abc; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Comparator;
public class TestSort2 { /* 请将A:1,C:8,D:1,B:3,B:1,F:1,E:5,Z:0,C:1...这样的一组数据进行按“:”的前半部分和后半部分排序 */ public static void main(String[] args) { Comparator comparator = new MyComparator(); List<Stri> list = new ArrayList<Stri>(); StringBuffer b = new StringBuffer(); String a = "A:1,C:8,D:1,B:3,B:1,F:1,E:5,Z:0,C:1"; String[] arr = a.split(","); for (int i = 0; i < arr.length; i++) { Stri str = new Stri(arr[i].split(":")[0], arr[i].split(":")[1]); list.add(str); } Collections.sort(list, comparator); Iterator iterator = list.iterator(); while (iterator.hasNext()) { Stri str = (Stri)iterator.next(); b.append(str.getLeftStr() + ":" + str.getRightStr() + ","); } System.out.print("排序后序列是:" + b); } } class Stri{ private String leftStr; private String rightStr; public Stri(String leftStr, String rightStr) { this.leftStr = leftStr; this.rightStr = rightStr; } public String getLeftStr() { return leftStr; } public void setLeftStr(String leftStr) { this.leftStr = leftStr; } public String getRightStr() { return rightStr; } public void setRightStr(String rightStr) { this.rightStr = rightStr; } } class MyComparator implements Comparator<Stri>{ public int compare(Stri str1, Stri str2) { int rs1 = str1.getLeftStr().compareTo(str2.getLeftStr()); int rs2 = str1.getRightStr().compareTo(str2.getRightStr()); int rs = -1; if (rs1 == rs2) { rs = rs1; } else if (rs1 > 0) { rs = 1; } else if (rs1 < 0) { rs = -1; } else if (rs1 == 0 && rs2 > 0) { rs = 1; } else if (rs1 == 0 && rs2 < 0) { rs = -1; } return rs; } } |