collectors常用方法

-- 伪数据
-- id,name,age,grade-- 年级,chineseScore-- 语文成绩,mathScore-- 数学成绩,englishScore-- 英语成绩
Student a = new Student(1, "a", 16, "高一", 120, 130, 125);
Student b = new Student(2, "b", 17, "高二", 80, 90, 80);
Student c = new Student(3, "c", 18, "高三", 130.1, 130, 100);
1.toCollection(collectionFactory)
 @Test
public void toCollectionTest() {
  //将学生年级放入集合
  TreeSet<String> grades = students.stream()
      .map(Student::getGrade).collect(Collectors.toCollection(TreeSet::new));
     System.out.println(grades.toString());
}
    //[高一, 高三, 高二]

2.toList()
@Test
public void toListTest() {
  //将学生名字放入集合
  List<String> names = students.stream()
      .map(Student::getName).collect(Collectors.toList());
        System.out.println(names.toString());
}

3.toSet()
@Test
public void toSetTest() {
  //将学生语文成绩放入集合
  Set<Double> chineseScores = students.stream()
      .map(Student::getChineseScore).collect(Collectors.toSet());
        System.out.println(chineseScores.toString());
}

4.toSet()
@Test
public void toSetTest() {
  //将学生语文成绩放入集合
  Set<Double> chineseScores = students.stream().map(Student::getChineseScore).collect(Collectors.toSet());
        System.out.println(chineseScores.toString());
}

5.toMap(keyMapper, valueMapper, mergeFunction)
-- toConcurrentMap也一样!
@Test
public void toMapWithMergeTest() {
  //将学生学号和班级放入map,当出现相同key时,用新值替换旧值
  Map<Long, String> map = students.stream().collect(Collectors.toMap(student -> student.getId(), student -> student.getGrade(), (oldValue, newValue) -> newValue));
        System.out.println(map.toString());
}

6.toMap(keyMapper, valueMapper, mergeFunction, mapSupplier)
@Test
public void toLinkedHashMapTest() {
  //将学生学号和班级放入自定义的LinkedHashMap
  LinkedHashMap<Long, String> map = students.stream().collect(Collectors.toMap(
        student -> student.getId(),
        student -> student.getGrade(),
        (oldValue, newValue) -> newValue,
            LinkedHashMap::new)
  );
        System.out.println(map.toString());
}

7.joining(delimiter, prefix, suffix)
@Test
public void joiningWithPrefixAndSuffixTest() {
  //将学生姓名用逗号连接成一个字符串,并在字符串前加上^^^,在字符串后加上$$$
  String names = students.stream().map(Student::getName).collect(Collectors.joining(",","^^^","$$$"));
        System.out.println(names);
        //结果:^^^a,b,c,d,e,f,g,h$$$
}

8.mapping( mapper, downstream)
@Test
public void mappingTest() {
  //将学生映射成学生名字,并收集到list中
   List<String> names = students.stream().collect(Collectors.mapping(Student::getName, Collectors.toList()));
        System.out.println(names.toString());
}

9.collectingAndThen(downstream, finisher)
@Test
public void collectingAndThenTest() {
   //先将学生年级收集到set中,再计算set的大小
   Integer count = students.stream().map(Student::getGrade).collect(Collectors.collectingAndThen(Collectors.toSet(), grade -> grade.size()));
        System.out.println(count);
}

10.counting()
@Test
public void countingTest() {
  //计算学生的数量
  Long count = students.stream().collect(Collectors.counting());
        System.out.println(count);
}

11.maxBy(comparator)
@Test
public void maxByTest() {
  //获取语文成绩最高分
  Optional<Double> max = students.stream().map(Student::getChineseScore).collect(Collectors.maxBy(Double::compare));
        System.out.println(max.get());
}

12.reducing(identity,mapper, op)
@Test
public void reducingTest() {
  //获取所有学生语文成绩总分
  Optional<Double> sum1 = students.stream().map(Student::getChineseScore).collect(Collectors.reducing(Double::sum));
  Double sum2 = students.stream().map(Student::getChineseScore).collect(Collectors.reducing(0d, Double::sum));
  Double sum3 = students.stream().collect(Collectors.reducing(0d, Student::getChineseScore, Double::sum));
  System.out.println(sum1.get());
  
13.partitioningBy(predicate, downstream)
@Test
public void partitioningByTest() {
  //按照年级分组后,再根据学生总成绩是否大于300分组
  Map<String, Map<Boolean, List<Student>>> map = students.stream().collect(
      //map<String,map> -- String对应 年级 grade
      Collectors.groupingBy(Student::getGrade,
      //map<boolean,list<>>
         Collectors.partitioningBy(
             //list
             student -> student.getChineseScore() + student.getEnglishScore() + student.getMathScore() > 300
        )
   )
);
        map.forEach((grade, map1) -> map1.forEach((b, list) ->
                list.stream().forEach(student -> System.out.println("grade: " + grade + " 是否大于300分: " + b + " id: " + student.getId())))
        );
    }
    
结果:
    grade: 高三 是否大于300分: true id: 3
    grade: 高三 是否大于300分: true id: 6
    grade: 高二 是否大于300分: false id: 2
    grade: 高二 是否大于300分: true id: 5
    grade: 高二 是否大于300分: true id: 8
                                                                                            






---- 
计数: count
平均值: averagingInt、 averagingLong、 averagingDouble
最值: maxBy、 minBy
求和: summingInt、 summingLong、 summingDouble
统计以上所有: summarizingInt、 summarizingLong、 summarizingDouble
/**
 * 统计员工人数、平均工资、工资总额、最高工资
 */
private static void test01(){
    //统计员工人数
    Long count = personList.stream().collect(Collectors.counting());
    //求平均工资
    Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
    //求最高工资
    Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
    //求工资之和
    Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
    //一次性统计所有信息
    DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
    System.out.println("统计员工人数:"+count);
    System.out.println("求平均工资:"+average);
    System.out.println("求最高工资:"+max);
    System.out.println("求工资之和:"+sum);
    System.out.println("一次性统计所有信息:"+collect);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值