Java 8 Stream List

发布于 2020-09-01 / Java / 0条评论 / 19浏览

Source

Student xm = new Student(); xm.setId(11); xm.setName("小明"); xm.setGender(1); Student xh = new Student(); xh.setId(12); xh.setName("小红"); xh.setGender(2); Student xt = new Student(); xt.setId(13); xt.setName("小天"); xt.setGender(1); List<Student> list = new ArrayList<>(); list.add(xm); list.add(xh); list.add(xt);

x01

Operate:

List<Integer> ids = list.stream().map(Student::getId).collect(Collectors.toList());

Result:

[11, 12, 13]

x02

Operate:

Map<Integer, String> idNames = list.stream().collect(Collectors.toMap(Student::getId, Student::getName));

Result:

{11: "小明", 12: "小红", 13: "小天"}

x03

Operate:

Map<Integer, Student> idMap = list.stream().collect(Collectors.toMap(Student::getId, Function.identity()));

Result:

{ 11: {"id": 11, "name": "小明", "gender": 1}, 12: {"id": 12, "name": "小红", "gender": 2}, 13: {"id": 13, "name": "小天", "gender": 1} }

x04

Operate:

Map<Integer, List<Student>> genderListMap = list.stream().collect(Collectors.groupingBy(Student::getGender));

Result:

{ 1: [{"id": 11, "name": "小明", "gender": 1}, {"id": 13, "name": "小天", "gender": 1}], 2: [{"id": 12, "name": "小红", "gender": 2}] }

x05

Operate:

Map<Integer, List<String>> genderListNameMap = list.stream().collect(Collectors.groupingBy(Student::getId, Collectors.mapping(Student::getName, Collectors.toList())));

Result:

{ 1: ["小明", "小天"], 2: ["小红"] }

more …

评论
站长统计