List<T>转另一个List<T>,List<T>转Map<T,T>,求和List<T>中T某一属性,获取List<T>中某一属性

List转另一个List,List转Map<T,T>,求和List中T某一属性,获取List中某一属性

Student类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private String id;
    private String name;
    private Integer age;
    private Integer sex;
    private Integer grade;
}

People类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class People {
    private String name;
    private Integer age;
    private Integer sex;
}

StreamTest类

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

public class StreamTest {
    public static void main(String[] args) {
        List<Student> studentList = Arrays.asList(
                new Student("1", "zs", 18, 1, 90),
                new Student("2", "ls", 20, 2, 92),
                new Student("3", "ww", 19, 1, 91),
                new Student("3", "ww", 19, 1, 91));
        /**
         * 1.List转为另一个List:Student -> People
         * 就是将Student中 name、age、sex属性赋予People
         */
        List<People> peopleList = studentList.stream()
                .map(u -> new People(u.getName(), u.getAge(), u.getSex())).collect(Collectors.toList());

        /**
         * 2.将studentList转为Map,以id作为key,实体作为value
         * 解释一下:
         * Student::getId,这里的意思就是获取Student的id属性作为Map中的key,想要其他属性作为key直接修改即可;
         * Function.identity(),固定写法,直接照搬即可(其实我也未具体了解过,大佬勿喷)
         * (k1, k2) -> k2),这个意思是当key重合时,用第二个key-value覆盖第一个key-value
         */
        Map<String, Student> studentMap = studentList.stream()
                .collect(Collectors.toMap(Student::getId, Function.identity(), (k1, k2) -> k2));
        /**
         * 3.获取Student中所有的id
         * 其实这种操作和上面的第一种一样,这里是获取Student中一个属性转为List
         */
        List<String> idList = studentList.stream().map(Student::getId).collect(Collectors.toList());

        /**
         * 4.获取Student中所有的id 去重
         * Set的特性之一就是不包括重复的元素,所有可以用来去重
         */
        Set<String> idSet = studentList.stream().map(Student::getId).collect(Collectors.toSet());


        /**
         * 5.计算所有Student的总分数,就是对Student的grade属性求和
         * mapToInt是对int类型求和,想对其他属性求和直接换一种方法就好。
         */
        Integer totalGrade = studentList.stream().mapToInt(Student::getGrade).sum();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值