Stream 根据集合内的对象某个属性值进行排序

2021/8/11 6:07:18

本文主要是介绍Stream 根据集合内的对象某个属性值进行排序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

import com.alibaba.fastjson.JSON;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * stream 流根据集合的某个字段属性进行排序
 */

public class streamDemo01 {

    public static void main(String[] args) {
        List<User> users = Arrays.asList(
                new User(101, "Jack"),
                new User(102, "Kreas"),
                new User(103, "Marry"),
                new User(104, "Timi"),
                new User(105, "Alice"));

        //自然序
        List<User> collect = users.stream().sorted(Comparator.comparing(User::getId)).collect(Collectors.toList());

        //倒序
        List<User> collect1 = users.stream().sorted(Comparator.comparing(User::getId).reversed()).collect(Collectors.toList());

        System.out.println(JSON.toJSONString(collect));
        System.out.println(JSON.toJSONString(collect1));

    }
}

输出结果:

[{"id":101,"name":"Jack"},{"id":102,"name":"Kreas"},{"id":103,"name":"Marry"},{"id":104,"name":"Timi"},{"id":105,"name":"Alice"}]
[{"id":105,"name":"Alice"},{"id":104,"name":"Timi"},{"id":103,"name":"Marry"},{"id":102,"name":"Kreas"},{"id":101,"name":"Jack"}]

@Data
public class User {
    // 用户ID
    private long id;

    // 用户名称
    private String name;

    public User(long id, String name) {
        this.id = id;
        this.name = name;
    }
}




这篇关于Stream 根据集合内的对象某个属性值进行排序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程