java取出list中的某几个属性组成一个新的集合的几种方式

2023-12-25 16:38:47

我用了三种方式,1:forEach循环;2:for循环;3:stream方法

package org.springblade.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Test {

    @org.junit.jupiter.api.Test
    public void aaa() {
        User user1 = new User("张三", 10, 1);
        User user2 = new User("李四 ", 11, 1);
        User user3 = new User("王五", 12, 0);
        List<User> users = new ArrayList<>();
        users.add(user1);
        users.add(user2);
        users.add(user3);
        //我这里都转为了List<Map<String, Object>>数组,也可以转换为一个新的实体类(自行创建)
        //使用forEach循环转化
        List<Map<String, Object>> infosFromForEach = new ArrayList<>();
        users.forEach(user -> {
            Map<String, Object> singleMap = new HashMap<>();
            singleMap.put("age", user.getAge());
            singleMap.put("gender", user.getGender());
            infosFromForEach.add(singleMap);
        });
        //使用for循环转化
        List<Map<String, Object>> infosFromFor = new ArrayList<>();
        for (User user : users) {
            Map<String, Object> singleMap = new HashMap<>();
            singleMap.put("age", user.getAge());
            singleMap.put("gender", user.getGender());
            infosFromFor.add(singleMap);
        }
        //使用stream流实现转换
        List<Map<String, Object>> collect = users.stream().map(user -> {
            Map<String, Object> singleMap = new HashMap<>();
            singleMap.put("age", user.getAge());
            singleMap.put("gender", user.getGender());
            return singleMap;
        }).collect(Collectors.toList());
    }


}

class User {
    //姓名
    private String name;
    //年龄
    private Integer age;
    //性别:0:女;1:男
    private Integer gender;

    public User() {
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public Integer getGender() {
        return gender;
    }

    public User setGender(Integer gender) {
        this.gender = gender;
        return this;
    }

}

文章来源:https://blog.csdn.net/weixin_49990593/article/details/135200792
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。