예제를 하나 더 늘려봤다.
List<Person> personList;
@BeforeEach
void setUp() {
...
personList = List.of(new Person("박병호","30"), new Person("최원태","20"), new Person("김상수", "30"));
}
...
@Getter
@Setter
private static class Person {
private String name;
private String age;
public Person(String name, String age) {
this.name = name;
this.age = age;
}
}
서른살의 박병호, 김상수와 스무살의 최원태를 Pesrson으로 만들어주었다.
personList.stream()
.map(s -> s.name)
.collect(Collectors.toList())
.forEach(s -> System.out.print(s + " ")); // 박병호 최원태 김상수
List<String> 형태로 Person의 name들만 뽑아서 리스트를 만들어준다.
List<Person> collect = personList.stream()
.filter(s -> s.age.equals("30"))
.collect(Collectors.toList());
filter로 30살인 선수들만 뽑았다.

이렇게 객체인 리스트가 생성된다. 이 선수들의 이름만 뽑고 싶다면? 아까처럼 Map을 사용하면 된다.
personList.stream()
.filter(s -> s.age.equals("30"))
.map(s -> s.name)
.collect(Collectors.toList());

원리는 알겠는데 사용할 때마다 항상 버벅인다ㅠ
flatMap
평탄화를 시켜주는 기능을 한다.
List<Map.Entry<String, String>> collect1 = mapList.stream()
.flatMap(s -> s.entrySet().stream())
.collect(Collectors.toList());

List<Map<String,String>> 형태였던 mapList에서 두개의 map을 하나로 합친 형태로 나온다.
그럼 여기서 filter, sort,map등을 자유롭게 사용하면 된다.
'TIL' 카테고리의 다른 글
프로그래머스 코딩테스트 연습_문자열 내 p와 y의 개수 Java (0) | 2023.11.15 |
---|---|
[TIL] 프로그래머스 숫자의 표현 효율성 테스트 실패ㅠㅠ (1) | 2023.11.03 |
[TIL] Stream API method 탐구, map과 filter (0) | 2023.10.24 |
[TIL] Spring Security 하나의 url에 두 개의 역할이 가능하도록 권한을 주고싶다 (0) | 2023.10.15 |
[TIL] 반성의 TIL... Junit MockMvc.perform 에서 session 사용하기.. (0) | 2023.10.12 |