Java stream常用实例代码

定义对象实体

package com.elon.model;

/**
 * 简单用户实体类
 *
 * @author elon
 */
public class User {

    /**
     * 用户账号
     */
    private String account = "";

    /**
     * 用户名
     */
    private String name = "";

    /**
     * 年龄
     */
    private int age = 0;

    public User() {

    }

    public User(String account, String name, int age){
        this.account = account;
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public int getAge() {
        return age;
    }

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

场景一 根据属性过滤对象

    /**
     * 使用流过滤数据.
     *
     * @author elon
     */
    public static void filterUser(List<User> userList) {
        // 1、过滤数据
        List<User> filterUserList = userList.stream().filter(u->u.getAge() > 12).collect(Collectors.toList());

        // 2、打印过滤结果数量
        System.out.printf("过滤后的数据:%s%n", new Gson().toJson(filterUserList));
    }

场景二 提取对象中的属性

    /**
     * 提取对象中的某个属性值。
     *
     * @param userList 用户对象列表
     * @author elon
     */
    public static void distillField(List<User> userList) {
        List<String> nameList = userList.stream().map(User::getName).collect(Collectors.toList());

        // 打印提取的用户名
        System.out.printf("打印提取的用户名:%s%n", new Gson().toJson(nameList));
    }

场景三 按对象属性分组

    /**
     * 根据某个属性对对象做分组.
     *
     * @param userList 用户列表
     * @auhtor elon
     */
    public static void groupUser(List<User> userList) {
        Map<Integer, List<User>> userMap = userList.stream().collect(Collectors.groupingBy(User::getAge));

        System.out.printf("分组后的对象:%s\n", new Gson().toJson(userMap));
    }
发布了113 篇原创文章 · 获赞 183 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/ylforever/article/details/104092996
今日推荐