java中对List进行分组和排序
排序
对List进行排序,有两种办法
第一个是用java提供的工具类Collections提供的sort方法进行排序
废话不多说,上代码
首先定义一个Student
public class Student { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Student(int age, String name) { super(); this.age = age; this.name = name; } }
下面是进行排序的代码
public static void main(String[] args) { List<Student> list= new ArrayList<Student>(); list.add(new Student(5, "aa")); list.add(new Student(7, "bb")); list.add(new Student(6, "cc")); Collections.sort(list,new Comparator<Student>(){ @Override public int compare(Student o1, Student o2) { //会把集合里面的对象两两传进方法里面比较,这里比较age,降序就O2-O1,升序就O1-O2 return o2.getAge()-o1.getAge(); } }); //打印list每一项的age list.forEach(a -> System.out.println(a.getAge())); } }
第二种方法:
List集合提供了sort方法,依然用Student做集合,进行排序
public static void main(String[] args) { List<Student> list= new ArrayList<Student>(); list.add(new Student(5, "aa")); list.add(new Student(7, "bb")); list.add(new Student(6, "cc")); //差别在这里,这里直接用list的sort方法,不需要吧list作为参数,其他的和Comparable排序是一样的 list.sort(new Comparator<Student>(){ @Override public int compare(Studento1, Studento2) { //会把集合里面的对象两两传进方法里面比较,这里比较age,降序就O2-O1,升序就O1-O2 return o2.getAge()-o1.getAge(); } }); //打印list每一项的age list.forEach(a -> System.out.println(a.getAge())); } }
对list进行分组:
同样的,用Student的集合作为示例,代码如下
public class test2 { /** * 创建比较器 */ public static <T> List<List<T>> dividerList(List<T> list,Comparator<? super T> comparator) { List<List<T>> lists = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { boolean isContain = false; for (int j = 0; j < lists.size(); j++) { if (lists.get(j).size() == 0||comparator.compare(lists.get(j).get(0),list.get(i)) == 0) { lists.get(j).add(list.get(i)); isContain = true; break; } } if (!isContain) { List<T> newList = new ArrayList<>(); newList.add(list.get(i)); lists.add(newList); } } return lists; } public static void main(String[] args) { List<Student> list = new ArrayList<Student>(); //实在不会起名字,用字母代替吧 list.add(new Student(17,"aa")); list.add(new Student(15,"bb")); list.add(new Student(16,"cc")); list.add(new Student(15,"dd")); list.add(new Student(16,"ee")); list.add(new Student(17,"ff")); List<List<Student>> list2 = dividerList(list, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { // 按年龄分组,这里注意一点,返回的值为0,就会认为这两个Studeng是一组的,返回其他值,则认为不是,所以下面的-1可以替换为任意非0数字 return o1.getAge == o2.getAge ? 0:-1; //也可以按照姓名分组,返回结果如下,因为是比较两个值是否相等,所以先后是没有区别的 //return o1.getName().compareTo(o1.getName()) } });
for(List<Student> stList: list2){
stList.forEach(a -> System.out.printIn(a.getName+":"+a.getAge));
System.out.printIn("=========================================");
}
} }