java8中Collectors的使用方法举例和Function<T,R>简介

Collectors 实现了接口 Collector<T,A,R>
T: 需要进行reduce操作的元素类型
A:reduce操作的动态集合类型
R:reduce操作的结果类型

  • 举例

//将名字集合到list

List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());

//将名字集合到TreeSet

Set<String> set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new));

//将名字转换为String,并连接为一个字符串

String joined = things.stream()
                           .map(Object::toString)
                           .collect(Collectors.joining(", "));

//计算员工的工资总额

int total = employees.stream()
                          .collect(Collectors.summingInt(Employee::getSalary)));

//根据部门将员工分组:

Map<Department, List<Employee>> byDept
         = employees.stream()
                    .collect(Collectors.groupingBy(Employee::getDepartment));

//计算不同部门的员工工资总额

Map<Department, Integer> totalByDept
         = employees.stream()
                    .collect(Collectors.groupingBy(Employee::getDepartment,
                                                   Collectors.summingInt(Employee::getSalary)));

//划分及格和不及格的学生

Map<Boolean, List<Student>> passingFailing =
         students.stream()
                 .collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));

Collectors的官方说明见:
官网文档

如果你对Function接口不是很了解,那么在使用这些方法时会很容易出错,下面进行简单的介绍:

Function<T, R>

T—函数的输入类型
R-函数的输出类型

也就是通过这个函数,可以将一个类型转换为另一个类型,比如下面的例子:

 //定义一个function 输入是String类型,输出是 EventInfo 类型,  EventInfo是一个类。           
Function<String, EventInfo> times2 = fun -> { EventInfo a = new EventInfo(); a.setName(fun); return a;};

String[] testintStrings={"1","2","3","4"}; 

//将String 的Array转换成map,调用times2函数进行转换
Map<String,EventInfo> eventmap1=Stream.of(testintStrings).collect(Collectors.toMap(inputvalue->inputvalue, inputvalue->times2.apply(inputvalue)));

如果Collectors.toMap的转换过程很简单,比如输入和输出类型相同,则不需要另外定义Function,例如:

Map<String,String> eventmap2=Stream.of(testStrings).collect(Collectors.toMap(inputvalue->inputvalue, inputvalue->(inputvalue+”a”)));
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值