java 8 list 按某字段排序

package com.ken.test;

import java.util.ArrayList;

import java.util.Comparator;

import java.util.List;

import java.util.stream.Collectors;

public class TestJava8List {

public static void main(String[] args) {

User user1 = new User(21,”张三”);

User user2 = new User(25,”李四”);

User user3 = new User(22,”王五”);

User user4 = new User(19,”赵柳”);

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

list.add(user1);

list.add(user2);

list.add(user3);

list.add(user4);

for(User u :list){

System.out.println(u);

}

List<User> newList = list.stream().sorted(Comparator.comparing(User::getAge))

                .collect(Collectors.toList());

for(User u :newList){

System.out.println(u);

}

}

}

class User {

private int age;

private String name;

public User(int i, String s) {

this.age = i;

this.name = s;

}

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;

}

@Override

public String toString() {

return “User [age=” + age + “, name=” + name + “]”;

}

}

运行结果:

User [age=21, name=张三]
User [age=25, name=李四]
User [age=22, name=王五]
User [age=19, name=赵柳]
User [age=19, name=赵柳]
User [age=21, name=张三]
User [age=22, name=王五]
User [age=25, name=李四]

    原文作者:一叶飘零_sweet_
    原文地址: https://blog.csdn.net/jam_yin/article/details/80981000
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞