@ToString
객체의 속성 값들을 콘솔에 출력
@RequestParam
아래 modelattribute에서 설명함
@ModelAttribute
@RequestParam과 달리 객체 자체를 매핑한다. @RequestParam는 객체의 속성을 각각 맵핑 해야되지만 @ModelAttribute는 객체 자체를 맵핑하기 때문에 만약 다른 속성이 추가된다면 수정이 용이하다.
@RequiredArgsConstructor
final이 붙거나 @NotNull 이 붙은 필드의 생성자를 자동 생성해주는 롬복 어노테이션
필드 주입방식을 사용한 기존 Service
@Service
public class BannerServiceImpl implements BannerService {
@Autowired
private BannerRepository bannerRepository;
@Autowired
private CommonFileUtils commonFileUtils;
@RequiredArgsConstructor 를 활용한 생성자 주입
@Service
@RequiredArgsConstructor
public class BannerServiceImpl implements BannerService {
private final BannerRepository bannerRepository;
private final CommonFileUtils commonFileUtils;
...
@RequiredArgsConstructor를 사용하지 않으면 원래는 이렇게 생성자 주입을 해야한다
@Service
public class BannerServiceImpl implements BannerService {
private BannerRepository bannerRepository;
private CommonFileUtils commonFileUtils;
@Autowired
public BannerServiceImpl(BannerRepository bannerRepository, CommonFileUtils commonFileUtils) {
this.bannerRepository = bannerRepository;
this.commonFileUtils = commonFileUtils;
}
...
Mapping
스트림내 요소들에 대해 함수가 적용된 결과의 새로운 요소로 매핑해준다.
준비하기
- sample data (Human)
번호, 이름, 가진돈, 생일, 여행, 지역
1 | jojae | 2900 | 1991-02-26 | seoul, hawai |
2 | haha | 1000 | 2003-03-02 | busan |
3 | arabia | 30000 | 2001-04-06 | seoul, paris |
4 | cici | 150 | 1982-05-16 | daegu, hongkong |
5 | zzang | 40000 | 1910-06-26 | gwangju |
6 | ssu | 200000 | 2012-07-11 | busan |
7 | kuku | 150 | 1991-02-27 | seoul, hawai |
8 | kuku | 2222 | 1998-07-27 | hawai |
public class Human implements Comparable<Human> {
private Long idx;
private String name;
private Integer money;
private LocalDate birth;
private List<String> travelDestinations;
}
기본 사용법
@DisplayName("이름만 가져와서 List 만들기")
void mapTest1() {
List<String> humanNames = humans.stream()
.map(h -> h.getName())
.collect(Collectors.toList());
for (String humanName : humanNames) {
System.out.print(humanName + " ");
}
}
- 결과
jojae haha arabia cici zzang ssu kuku kuku
중복제거
distinct()를 이용하여 중복제거 가능
@DisplayName("중복제거")
void mapTest2() {
printHumanNames(humans);
List<String> names = humans.stream()
.map(h -> h.getName())
.distinct()
.collect(Collectors.toList());
System.out.println();
for (String name : names) {
System.out.print(name + " ");
}
}
- 결과
jojae haha arabia cici zzang ssu kuku kuku jojae haha arabia cici zzang ssu kuku
출처: https://isntyet.github.io/java/java-stream-%EC%A0%95%EB%A6%AC(map)/
'웹 개발 > Back End' 카테고리의 다른 글
Spring REST Docs (0) | 2022.09.15 |
---|---|
스프링 개념 정리(3) (0) | 2022.09.01 |
스프링 개념 정리(1) (0) | 2022.08.27 |
실전! 스프링 부트와 JPA 활용2 - 스프링 데이터 JPA, QueryDSL 소개 (0) | 2022.01.28 |
실전! 스프링 부트와 JPA 활용2 - API 개발 고급 - 컬렉션 조회 최적화 (0) | 2022.01.26 |
댓글