StreamAPI,取出list中的name属性,返回一个新list

使用 Stream API 从列表中提取 name 属性并返回一个新列表,可以通过以下步骤实现:首先将列表转换为流,然后使用 map 方法将流中的每个元素映射为其 name 属性,最后使用 collect 方法结合 Collectors.toList() 将映射后的元素收集到一个新列表中。

以下是一个示例代码:

java 复制代码
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

class User {
    private int id;
    private String name;
    private String password;

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

    public String getName() {
        return name;
    }
}

public class StreamExample {
    public static List<User> getUserList() {
        List<User> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(new User(i + 11, "name_00" + i, "test_0" + i));
        }
        return list;
    }

    public static void main(String[] args) {
        List<User> userList = getUserList();
        // 从列表中提取name属性并返回新列表
        List<String> nameList = userList.stream()
                .map(User::getName)
                .collect(Collectors.toList());
        System.out.println(nameList);
    }
}

在上述代码中,userList.stream()userList 转换为流,map(User::getName) 将流中的每个 User 对象映射为其 name 属性,collect(Collectors.toList()) 将映射后的 name 属性收集到一个新的列表中。

相关推荐
m0_547486662 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr2 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_32 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.2 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.2 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣2 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9922 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
淡海水2 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1012 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
2401_839080542 天前
C++常见八股
数据结构·c++·算法