자바를 자바바
Stream
: 함수 여러 개를 조합하여 필터링, 맵핑된 결과를 얻게 할 수 있도록 함
1️⃣ 배열의 원소를 가공하는 방법
- map: 요소들을 특정 조건에 해당하는 값으로 변환함
- filter: 요소들을 조건에 따라 걸러내는 작업을 함
- sorted 요소들을 정렬하는 작업을 함
위와 같은 가공이 끝나면, 리턴해줄 결과를 collect를 통해 만들어준다
2️⃣ 실전
test SET
ArrayList<string> list = new ArrayList<>(Arrays.asList("KIM", "GYU", "RY"));
1. map
list.stream().map(s->s.toUpperCase());
list.stream().map(String:toUpperCase);
System.out.print(list.stream()
.map(->s.toUpperCase()).collect(Collectors.joining(" ")));
System.out.print(list.stream()
.map(->s.toUpperCase()).collect(Collectors.toList(" ")));
System.out.print(list.stream()
.map(String:toUpperCase).collect(Collectors.toList(" ")));
List.stream().map(String::toUpperCase).forEach(s -> System.out.println(s));
- 요소들을 대문자로 변경해주었다 ()
- Collectors.joining : 리스트의 조인 기준으로 배치 가능 (String으로 리턴함)
- 출력결과: KIM GYU RY
- Collectors.toList: 리스트로 리턴받음
- 출력결과: [KIM, GYU, RY]
- forEach: 요소마다 각각 작업 가능
- 출력결과:
- KIM
- GYU
- RY
2. filter
list.stream().filter(t->t.length()>2)
System.out.println(list.stream().filter(t->t.length()>2).collect(Collectors.joning(" ")));
System.out.println(list.stream().filter(t->t.length()>2).collect(Collectors.toList()));
- 요소를 특정 기준으로 걸러내며, 여기선 크기가 2 이상인 것만 뽑아낸다
- 출력결과: Kim gyu [Kim, gyu]
3. sorted
list.stream().sorted()
System.out.println(list.stream().sorted().collect(Collectors.toList()));
- 리스트의 요소를 정렬함
- 출력결과: [Gyu, Kim, Ri]