java8 Stream分组用法

简介

今天在开发中遇到一个分组的问题,因为当时数据库的用的JPA开发的,当时我不想去写原生的SQL来进行分组处理。所以就查询了jdk8中的分组。先看一个分组的例子:

@Data
public class Student {
    private String name;
    private int age;
    private int code;

    public Student(String name, int age, int code) {
        this.name = name;
        this.age = age;
        this.code = code;
    }

    public static void main(String[] args) {
        Student student = new Student("小名",20,115);
        Student student1 = new Student("小名",24,115);
        Student student2 = new Student("小名",20,115);

        List<Student> studentList = Arrays.asList(student, student1, student2);

        //按照年龄分组
        Map<Integer, List<Student>> ageMap = studentList.stream().collect(Collectors.groupingBy(Student::getAge));
        System.out.println("ageMap = " + ageMap);

        //按照年龄分组,并求出个数
        Map<Integer, Long> ageMap2 = studentList.stream().collect(Collectors.groupingBy(Student::getAge, Collectors.counting()));
        System.out.println("ageMap2 = " + ageMap2);

    }
}

开发中的代码:

    public List<AreaDeviceConfigDTO> areaList() {
        List<DeviceConfig> deviceConfigs = deviceConfigRepository.findAll();
        Map<ParkingLot, List<DeviceConfig>> listMap = deviceConfigs.stream().collect(Collectors.groupingBy(DeviceConfig::getParkingLot));
        List<AreaDeviceConfigDTO> deviceConfigDTOS = Lists.newArrayList();
        for (Map.Entry<ParkingLot, List<DeviceConfig>> entry : listMap.entrySet()) {
            AreaDeviceConfigDTO areaDeviceConfigDTO = new AreaDeviceConfigDTO();
            ParkingLot parkingLot = entry.getKey();
            areaDeviceConfigDTO.setId(parkingLot.getId());
            areaDeviceConfigDTO.setParkingLotName(parkingLot.getParkingLotName());
            areaDeviceConfigDTO.setMain(parkingLot.isMain());
            areaDeviceConfigDTO.setDeviceConfigs(entry.getValue());
            deviceConfigDTOS.add(areaDeviceConfigDTO);
        }

        return deviceConfigDTOS;
    }

ps:更多的信息请参考JDK8中的stream的用法

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,099评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,966评论 25 709
  • 撰写一个优秀的个案案例,是个案社工的必备技能。优秀的个案案例要体现个案服务方法的专业性、服务成效的显著性、个案故事...
    心理师吴非阅读 26,317评论 0 3
  • 说到花,不得不讲到花道, 所谓“花道”就是适当地截取树木花草的枝、叶、花朵插入花瓶等花器中的方法和技术, 并能给人...
    Anna安娜_吴阅读 342评论 0 0
  • 鲁定公的时候,为了巩固加强君主的权力,开始拆除世家贵族封地的城墙。 在拆除城墙的过程中,遭到了公山不狃和叔孙辄的顽...
    寒七琪阅读 1,230评论 0 1