java Collections.sort()实现List排序自定义方法
Posted 求知若渴 虚心若愚
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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排序自定义方法的主要内容,如果未能解决你的问题,请参考以下文章
java Collections.sort()实现List排序自定义方法
java Collections.sort()实现List排序的默认方法和自定义方法
java Collections.sort()实现List排序的默认方法和自定义方法
java list排序的两种方式(实现Comparable接口和Collections.sort重载方法)