본문 바로가기

IT/개발

JAVA 8 groupingBy, mapping, collectingAndThen

List<T>로 return 되는 데이터에 grouping 해야될 일이 생겼습니다.

소스나 구글링중 groupingBy 함수를 봤던지라 크게 어려움을 느끼지 않고
groupingBy를 써서 key로 해당데이터의 특정값으로 groupingBy를 했습니다.
Map<Integer, List<T>>로 정상적으로 return 성공

이 데이터에서 map.get(key) 를 했을때 
리턴되는 list에서 정렬후 하나의 값만 조회하는 비즈니스 로직을 만들어야 했습니다.
소스로 공유를 드리겠습니다.

1
2
3
4
5
public interface StudentDataDao {
    
    List<StudentData> selectStudentDataListByStuIds(@Param("stuIds") List<Integer> stuIds);
    
}
cs
1
2
3
4
5
6
7
8
@Service
public class StudentQueryService {
    
   public List<Data> getStudentListByStuIds(List<Integer> stuIds) {
        return studentDataDao.selectStudentDataListByStuIds(stuIds);
   }
    
}
cs

 

실제 구현로직을 보면 매우 간단하게?
처리되는것을 볼 수 있습니다.
저도 참조하면서 만든소스라 처음에는 보기에 어려웠으나
몇시간정도 눈에 익히고 따라하다보니 
가독성면에서 좋다는것을 알게 되었습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Service
public class ModuleQueryService {
    
   public Map<Integer, Student> getStudentData(List<Integer> stuIds) {
        return studentQueryService.getStudentListByStuIds(stuIds)
                .stream()
                .collect(groupingBy(    /*grouping으로 Map<Integer, List<Student>> 로 return된다.*/
                        StudentData::getStuId, mapping(    /*mapping함수를 이용해서 List<Student>를 student로 mapping한다. */
                                studata -> studata, collectingAndThen(    /*mapping의 첫번째 파라미터는 Function함수라서 lambda형태로 사용할수 있으며, List<Studata>를 그대로 전달해준다.어디로?
                                                                          collectingAndThen으로 collectingAndThen의 두번째 파라미터로 람다형태의 Function 함수가 들어갈수 있다.*/                                         
                                        Collectors.toList(), list -> {  /*grouping해서 return되면 List<T>라서 Collectors.toList()로 선언해준다. (다음 파라미터에서 사용)*/
                                                return list.stream()    
                                                .max(Comparator.comparing(StudentData::getRegDt))/*등록일자로 정렬해서 최근일자중 하나를 선택한다. max = sorted().reversed().findFirst()*/
                                                .orElse(ConsultView.builder().build());
                                        })
                        )
                ));
   }
    
}
cs

 

 

'IT > 개발' 카테고리의 다른 글

Kafka  (0) 2021.10.12
spring test spy 활용하기  (0) 2021.03.04
spring junit void test  (0) 2020.12.01
spring file delete  (0) 2020.10.29
spring 파일 다운로드  (0) 2020.10.28