상세 컨텐츠

본문 제목

[Kotlin] forEach / for EachIndexed

프로그래밍

by 독서와 여행 2021. 4. 8. 21:25

본문

list.forEach{print("$it")} // 출력 1 2 3 4 5 6
list.forEachIndexed{index, value -> println("index[$index]: $value")}
list.onEach{print(it)} // 출력123456 각 요소를 람다식으로 처리 후 컬렉션으로 반환

forEach 잘 쓰면 좋아 보인다. for문을 사용하지 않아도 되네

 

forEachIndexed는 인덱스랑 value를 받을 수 있다.

 

onEach 도 있네 차이점에 대해 공부해 보자 forEach랑 무슨 차이일까

 

forEach -> 각 요소를 람다식으로 처리 // onEach -> 각 요소를 람다식으로 처리 후 컬렉션으로 반환

 

println(list.count{it % == 2}) //와 이게되네 이정도면 파이썬보다 편한데?

 

 

관련글 더보기

댓글 영역