方法一:
package testSimple; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; public class testCollectionSort {
public static void main(String[] args) {
List<TblPowerGroup> list = new ArrayList<TblPowerGroup>();
list.add(new TblPowerGroup("100001", "cxx1"));
list.add(new TblPowerGroup("100002", "cxx2"));
list.add(new TblPowerGroup("100003", "cxx6"));
list.add(new TblPowerGroup("100003", "cxx5"));
list.add(new TblPowerGroup("100004", "cxx5"));
list.add(new TblPowerGroup("100004", "cxx6"));
Collections.sort(list, new Comparator<TblPowerGroup>() { @Override
public int compare(TblPowerGroup o1, TblPowerGroup o2) {
if (o1.getGroupSn().compareTo(o2.getGroupSn()) == 0) {
return o1.getNodeName().compareTo(o2.getNodeName());
} else {
return o1.getGroupSn().compareTo(o2.getGroupSn());
}
} });
System.out.println(list);
}
} class TblPowerGroup {
private String groupSn;
private String nodeName; public TblPowerGroup(String groupSn, String nodeName) {
super();
this.groupSn = groupSn;
this.nodeName = nodeName;
} public String getGroupSn() {
return groupSn;
} public void setGroupSn(String groupSn) {
this.groupSn = groupSn;
} public String getNodeName() {
return nodeName;
} public void setNodeName(String nodeName) {
this.nodeName = nodeName;
} @Override
public String toString() {
return "TblPowerGroup [groupSn=" + groupSn + ", nodeName=" + nodeName
+ "]";
} }
方法二:
package testSimple; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; public class testCollectionSort2 {
public static void main(String[] args) {
List<TblPowerGroup> list = new ArrayList<TblPowerGroup>();
list.add(new TblPowerGroup("100001", "cxx1"));
list.add(new TblPowerGroup("100002", "cxx2"));
list.add(new TblPowerGroup("100003", "cxx6"));
list.add(new TblPowerGroup("100003", "cxx5"));
list.add(new TblPowerGroup("100004", "cxx5"));
list.add(new TblPowerGroup("100004", "cxx6"));
Collections.sort(list, new TblPowerGroupSort());
System.out.println(list);
} private static class TblPowerGroupSort implements Comparator<TblPowerGroup> { @Override
public int compare(TblPowerGroup o1, TblPowerGroup o2) {
if (o1.getGroupSn().compareTo(o2.getGroupSn()) == 0) {
return o1.getNodeName().compareTo(o2.getNodeName());
} else {
return o1.getGroupSn().compareTo(o2.getGroupSn());
}
} }
}