简介
今天在开发中遇到一个分组的问题,因为当时数据库的用的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的用法