TIL

[Java] stream

승무_ 2023. 2. 15. 14:49

filter

스트림내 요소에 대해서 필터링하는 작업

 

public class Human {
    private Long idx;
    private String name;
    private Integer money;
    private LocalDate birth;
}
@DisplayName("돈이 2000원 이상인 사람 전부")
void filterTest3() {
    List<Human> tmpHumans = humans.stream()
            .filter(h -> h.getMoney() > 2000)
            .collect(Collectors.toList());
}

 

map

스트림내 요소들에 대해 함수가 적용된 결과의 새로운 요소로 매핑

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 + " ");
    }
}

중복제거

@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 + " ");
    }
}

내부요소에 대한 평면화 (flatMap)

flatMap 을 이용하면 스트림이 아니라 스트림의 콘텐츠로 매핑이 가능함.
map으로 travelDestinations으로 변환하였지만 해당값 자체가 List<String> 이기때문에
여행지 하나하나에 대한 중복제거를 할수 없었지만

flatMap을 이용해서 다시 스트림내의 컨텐츠를 가져와 매핑하였기에 중복제거를 가능하게 함.

@DisplayName("다녀온 여행지 종합")
void mapTest3() {
    printHumanTravelDestination(humans);

    List<String> travelDestinations = humans.stream()
            .map(h -> h.getTravelDestinations())
            .flatMap(Collection::stream)
            .distinct()
            .collect(Collectors.toList());

    for (String travelDestination : travelDestinations) {
        System.out.print(travelDestination + " ");
    }
}
//결과 

[seoul, hawai]
[busan]
[seoul, paris]
[daegu, hongkong]
[gwangju]
[busan]
[seoul, hawai]
[hawai]

seoul hawai busan paris daegu hongkong gwangju

'TIL' 카테고리의 다른 글

[Sql] 문자 함수  (0) 2023.03.01
[Spring] 토큰 만료 예외처리  (0) 2023.02.17
[Java] 두 날짜 차이 계산  (0) 2023.02.14
[Spring] CORS 허용하는 방법  (0) 2023.02.10
[Web] CORS  (0) 2023.02.09