TIL

[TIL] Stream API method 탐구2, 객체 리스트와 map, flatMap

봄봄로그 2023. 10. 27. 19:52

예제를 하나 더 늘려봤다.

       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등을 자유롭게 사용하면 된다.