java8流式编程统计属性相同个数大于1的数据

该代码示例展示了一个Java程序,它创建了一个Student对象的列表,然后使用StreamAPI和Collectors对列表进行操作。首先,通过groupingBy方法按学生所在城市进行分组并计算每个城市的数量。接着,筛选出城市数量大于1的学生,最后返回包含这些城市的所有学生列表。
摘要由CSDN通过智能技术生成
import com.google.common.collect.Lists;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        Student student = new Student("张三", "北京");
        Student student2 = new Student("李四", "北京");
        Student student3 = new Student("王五", "郑州");
        Student student4 = new Student("赵六", "北京");
        ArrayList<Student> list = Lists.newArrayList();
        list.add(student);
        list.add(student2);
        list.add(student3);
        list.add(student4);
        //1.统计department属性相同的个数
        Map<String, Long> countByDepartment = list.stream()
                .collect(Collectors.groupingBy(Student::getCity, Collectors.counting()));
        //2.筛选统计结果大于1个的数据
        Map<String, Long> statisticsData = countByDepartment.entrySet().stream()
                .filter(entry -> entry.getValue() > 1)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        //3.返回需要的数据
        List<Student> result = list.stream().filter(param -> statisticsData.keySet().contains(param.getCity()))
                .collect(Collectors.toList());
        System.out.println(result);
    }
}

@Data
class Student{
    private String name;
    private String city;

    public Student(String name,String city){
        this.name = name;
        this.city = city;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值