面试回顾——List<T>排序

 

1、如何对List<T>排序:

public static void main(String[] args) {
        Student stu1=new Student("张三","男",25);
        Student stu2=new Student("李四","男",22);
        Student stu3=new Student("王五","男",26);
        Student stu4=new Student("赵六","男",25);
        Student stu5=new Student("麻七","男",28);
        Student stu6=new Student("二狗","男",21);
        List<Student> list=new ArrayList<Student>();
        list.add(stu1);list.add(stu2);
        list.add(stu3);list.add(stu4);
        list.add(stu5);list.add(stu6);
         
        System.out.println("排序前:");
        for (Student student : list) {
            System.out.println(student.toString());        
        }
        Collections.sort(list, new Comparator<Student>(){
            @Override
            public int compare(Student o1, Student o2) {
                if(o1.getStuAge()>o2.getStuAge()){
                    return 1;
                }
                if(o1.getStuAge()==o2.getStuAge()){
                    return 0;
                }
                return -1;
            }          
        });
        System.out.println("排序后:");
        for (Student student : list) {
            System.out.println(student.toString());        
        }
    }

Java8新流式排序:

package com.concretepage;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class SortList {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<Student>();
        list.add(new Student(1, "Mahesh", 12));
        list.add(new Student(2, "Suresh", 15));
        list.add(new Student(3, "Nilesh", 10));
//以自然序排序一个list System.out.println(
"---Natural Sorting by Name---"); List<Student> slist = list.stream().sorted().collect(Collectors.toList()); slist.forEach(e -> System.out.println("Id:"+ e.getId()+", Name: "+e.getName()+", Age:"+e.getAge()));
//自然序逆序元素,使用Comparator提供的reverseOrder()方法 System.out.println(
"---Natural Sorting by Name in reverse order---"); slist = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()); slist.forEach(e -> System.out.println("Id:"+ e.getId()+", Name: "+e.getName()+", Age:"+e.getAge()));
//使用Comparator来排序一个list System.out.println(
"---Sorting using Comparator by Age---"); slist = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList()); slist.forEach(e -> System.out.println("Id:"+ e.getId()+", Name: "+e.getName()+", Age:"+e.getAge()));
//把上面的元素逆序 System.out.println(
"---Sorting using Comparator by Age with reverse order---"); slist = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList()); slist.forEach(e -> System.out.println("Id:"+ e.getId()+", Name: "+e.getName()+", Age:"+e.getAge())); } }

 

posted @ 2018-06-28 17:20  三尺墨  阅读(237)  评论(0编辑  收藏  举报