[JAVA] Stream_ map() 과 flatMap() 차이

2023. 11. 29. 20:02백엔드/JAVA

728x90

 

 

map()

-입력: 배열

        String[] arr = new String[]{"AA", "BB", "CC"};

-출력: List<String[]>

      {{"A","A"},{"B","B"},{"C","C"}}

//예시코드
String[] arr = new String[]{"AA", "BB", "CC"};
List<String[]> mapStream = Arrays.stream(arr).peek(p->System.out.println("peek1:"+p)).
    map(m->m.split("")).peek(p->System.out.println("peek2:"+p)).collect(Collectors.toList());
//mapStream.stream().forEach(System.out::println);
for (int i = 0; i < mapStream.size(); i++) {
    for (int j = 0; j< mapStream.get(0).length; j++) {
        System.out.print("~~[" + i + ","+ j +"]::" + mapStream.get(i)[j]+", ");
    }
}

//출력

 

flatMap

-입력: 배열

        String[] arr = new String[]{"AA", "BB", "CC"};

-출력: List

      {"A","A","B","B","C","C"}

//flatMap예시코드
String[] arr = new String[]{"AA", "BB", "CC"};
List<String> flatMapStream = Arrays.stream(arr).peek(p->System.out.println("peek1:"+p))
    .map(m->m.split("")).peek(p->System.out.println("peek2:"+p))
    .flatMap(f->Arrays.stream(f)).peek(p->System.out.println("peek3:"+p))
    .collect(Collectors.toList());
    
//출력
peek1:AA
peek2:[Ljava.lang.String;@2ff4acd0
peek3:A
peek3:A
peek1:BB
peek2:[Ljava.lang.String;@54bedef2
peek3:B
peek3:B
peek1:CC
peek2:[Ljava.lang.String;@5caf905d
peek3:C
peek3:C

 

 

참고 : https://devjem.tistory.com/41

728x90

'백엔드 > JAVA' 카테고리의 다른 글

[JAVA] 람다(Lamda)  (0) 2023.12.13
[JAVA] Stream_ (2) Stream 중간연산  (2) 2023.11.29
[JAVA] Stream_ (1) Stream 생성  (2) 2023.11.28
[JAVA] 맥북 자바 완적 삭제  (0) 2023.03.27
[설치] JDK 버전 변경 방법  (0) 2023.03.08