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();
}
}