码迷,mamicode.com
首页 > 编程语言 > 详细

java1.8特性之多重排序简单示例

时间:2019-01-26 18:56:24      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:port   cti   实体   ide   reac   googl   oid   sys   png   

1. 实体类:Student.java

package java8newfeture;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import com.google.common.collect.Lists;

/**
 * @author zero 2019/01/26
 */
public class Student {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Student() {

    }

    /**
     * @param id
     * @param name
     */
    public Student(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + "]";
    }

}

2. 测试类:SortStudent.java

package java8newfeture;

import java.util.ArrayList;
import java.util.Comparator;

import com.google.common.collect.Lists;

/**
 * @author zero 2019/01/26
 */
public class SortStudent {

    public static void main(String[] args) {
        ArrayList<Student> students =
            Lists.newArrayList(new Student(1, "A2"),new Student(1, "A1"), new Student(3, "C3"), new Student(2, "B2"));
        // 默认是升序排序,降序为comparing(Student::getId).reversed().thComparing(Student::getName)
// 如果是需要按照某个字段降序排序,则在后面调用方法reversed() students.sort(Comparator.comparing(Student::getId).thenComparing(Student::getName)); students.forEach(System.out::println); } }

3. 测试结果:

技术分享图片

4. 结论:亲测有效,请自己扩展尝试!

java1.8特性之多重排序简单示例

标签:port   cti   实体   ide   reac   googl   oid   sys   png   

原文地址:https://www.cnblogs.com/superdrew/p/10324469.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!