首页 > 代码库 > java Collections.sort()实现List排序自定义方法
java Collections.sort()实现List排序自定义方法
方法一:
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()); } } } }
java Collections.sort()实现List排序自定义方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。