我是靠谱客的博主 靓丽网络,这篇文章主要介绍java collectors,现在分享给大家,希望可以做个参考。

定义一个实体类Student

复制代码
1
2
3
4
5
6
7
@Data @AllArgsConstructor public class Student { private int age; private String name; }

定义一个list

复制代码
1
2
3
4
5
List<Student> list = new ArrayList<>(); list.add(new Student(12,"a")); list.add(new Student(13,"b")); list.add(new Student(12,"c"));

list 转 map

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Map<String, Student> map= list.stream().collect(Collectors.toMap(new Function<Student, String>() { @Override public String apply(Student student) { // 返回值为map key return student.getName(); } }, new Function<Student, Student>() { @Override public Student apply(Student student) { // 返回值为map value return student; } })); lamda 写法 Map<String, Student> collect = list.stream(). collect(Collectors.toMap(Student::getName, student -> student));

结果

{a=Student(age=12, name=a), b=Student(age=13, name=b), c=Student(age=12, name=c)}

Collectors.toMap 有三个重载方法:

复制代码
1
2
3
4
5
6
toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper); toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction); toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier);

keyMapper:Key 的映射函数

valueMapper:Value 的映射函数

mergeFunction:当 Key 冲突时,调用的合并方法

mapSupplier:Map 构造器,在需要返回特定的 Map 时使用

当key 有想相同的时候 需要使用第二个重载方法

复制代码
1
2
3
4
5
6
7
8
9
Map<String, Student> collect = list.stream().collect(Collectors.toMap(Student::getName, student -> student, new BinaryOperator<Student>() { @Override public Student apply(Student t, Student t2) { //处理需要返回的数据 return t; } }));

第四个参数(mapSupplier)用于自定义返回 Map 类型,比如我们希望返回的 Map 是根据 Key 排序的,可以使用如下写法:

复制代码
1
2
3
4
5
6
7
TreeMap<String, Student> collect = list.stream(). collect(Collectors.toMap(Student::getName, student -> student, (t, t2) -> t, (Supplier<TreeMap<String, Student>>) TreeMap::new));

参考Java8 中 List 转 Map(Collectors.toMap) 使用技巧


List里面的对象元素,以某个属性来分组
以年龄分组

复制代码
1
2
3
4
5
6
7
8
9
Map<Integer, List<Student>> collect1 = list.stream(). collect(Collectors.groupingBy(new Function<Student, Integer>() { @Override public Integer apply(Student student) { //处理逻辑 return student.getAge(); } }));

结果

{12=[Student(age=12, name=a), Student(age=12, name=c)], 13=[Student(age=13, name=b)]}


获取list 里对象处理之后组成新的list

复制代码
1
2
3
List<String> collect = list.stream(). map(Student::getName).collect(Collectors.toList());

结果

[a, c, b]

复制代码
1
2
3
4
List<Student> collect = list.stream(). peek(student -> student.setName("姓名"+student.getName())).collect(Collectors.toList());

结果

[Student(age=12, name=姓名a), Student(age=12, name=姓名c), Student(age=13, name=姓名b)]

最后

以上就是靓丽网络最近收集整理的关于java collectors的全部内容,更多相关java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部