List对象数组排序(根据指定的属性)

话不多说直接上代码

/**
 * @author 633805 LYH
 * @version V1.0
 * @description 对类的描述
 * @create 2019-02-26 14:23
 * @since 1.7
 */
public class User {

    private Long uid;

    private String name;

    private Integer age;

    public User(Long uid, String name, Integer age) {
        this.uid = uid;
        this.name = name;
        this.age = age;
    }

    public Long getUid() {
        return uid;
    }

    public void setUid(Long uid) {
        this.uid = uid;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", Name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 633805 LYH
 * @version V1.0
 * @description 对类的描述
 * @create 2019-02-21 11:49
 * @since 1.7
 */
public class C {
    public static void main(String[] args) {

        //构造user对象
        User user1 = new User(1L, "lyh",21);

        User user2 = new User(2L, "abc",18);

        List<User> list = new ArrayList<User>();

        list.add(user1);
        list.add(user2);

        list.forEach(System.out::println);

        //方法一 根据年龄进行排序

       List<User> sortList =  list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
        //打印
        sortList.forEach(System.out::println);

        //方法二  根据年龄进行排序
        Collections.sort(list, (Comparator) (o1, o2) -> {
            User u1 = (User) o1;
            User u2 = (User) o2;
            return u1.getAge().compareTo(u2.getAge());
        });

        //打印
        list.forEach(System.out::println);

    }
}

 

 

发布了60 篇原创文章 · 获赞 57 · 访问量 20万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览