ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • List.of()
    Java 2023. 1. 30. 12:51

    List.of()는 배열들(Arrays)을 List로 변환할 때 사용한다.

    @Test
        @DisplayName("글 여려개 조회")
        void getList(){
            //given
            boardRepository.saveAll(List.of(
                    SpringBoard.builder()
                            .title("제목3")
                            .content("내용3")
                            .build(),
    
                    SpringBoard.builder()
                            .title("제목2")
                            .content("내용2")
                            .build(),
    
                    SpringBoard.builder()
                            .title("제목")
                            .content("내용")
                            .build()
            ));
    
            //when
            List<PostResponse> list = boardService.getList();
    
            //then
            assertEquals(3, list.size());
        }

     

     

    위 로직에선

                SpringBoard.builder()
                            .title("제목3")
                            .content("내용3")
                            .build()

    와 같은 객체가 3개가 존재하는데, 이를 boardRepository.save()로 세번 반복해서 처리해줄 수 있지만 List.of()를 이용해서 더 간편하고 가독성 있게 저장한다.

     

    List.of() 이외에도 Array.asList()라는 메서드가 존재한다. 

    'Java' 카테고리의 다른 글

    builder 패턴  (0) 2023.03.16
    length, length(), size() 차이  (0) 2023.01.30
    stream()  (0) 2023.01.30
    람다(lambda)  (2) 2023.01.30
    Java 오버로딩과 오버라이딩  (0) 2022.01.05
Designed by Tistory.