Stream 이란?
연속된 정보를 처리할 때 사용된다. 배열에서는 스트림 사용 불가, 컬렉션에서만 사용가능

- 스트림 생성 : 컬렉션 목록들을 스트림 객체로 변환해준다. (stream 메소드도 Collection 인터페이스에 선언되어있음)
- 중개 연산 : 생성된 스트림 객체를 어떻게 처리해야 할 지 명시해줘야된다. (아무런 결과도 리턴받지 못하기 때문에 종단연산을 만들어줘야된다.) , 중개연산은 없어도 상관 X
- 종단 연산 : 중개연산에서 작업을 통해 결과를 리턴해 준다.
자주 사용되는 Stream 연산자 종류(map, filter, forEach)
forEach()
stream에서 사용하는 반복문 이라고 생각하면된다.
public class StudentForEachSample {
public static void main(String[] args) {
StudentForEachSample sample = new StudentForEachSample();
List<StudentDTO> list = new ArrayList<>();
list.add(new StudentDTO("요다", 10, 99, 80));
list.add(new StudentDTO("만두", 12, 90, 85));
list.add(new StudentDTO("건빵", 13, 80, 75));
sample.printStudentName(list);
}
public void printStudentName(List<StudentDTO> list) {
list.stream().forEach(x -> System.out.println(x.getName() + " " + x.getAge()));
// list.stream().map(student -> student.getName()).forEach(System.out::println);
}
}
결과 :
요다 10
만두 12
건빵 13
map()
특정 데이터로 변환 해준다 예시로 DTO를 객체로 치환) `map()` 메소드는 Stream 사용시 정말 많이 사용하니 꼭 알아두자.
public class StudentMapSample {
public static void main(String[] args) {
StudentMapSample sample = new StudentMapSample();
List<StudentDTO> student = new ArrayList<>();
student.add(new StudentDTO("요다1", 10, 99, 80));
student.add(new StudentDTO("만두2", 12, 90, 85));
student.add(new StudentDTO("건빵3", 13, 80, 75));
List<String> result = sample.printGetName(student);
for (String s : result) {
System.out.println(s);
}
}
public List<String> printGetName(List<StudentDTO> student) {
//map 으로 변경하여 Name 값만 출력해보자
List<String> list = student.stream().map(x -> x.getName()).collect(Collectors.toList());
return list;
}
}
결과 :
요다1
만두2
건빵3
filter()
필요한 데이터를 걸러서 사용한다.
public class StudentFilterSample {
public static void main(String[] args) {
StudentFilterSample sample = new StudentFilterSample();
List<StudentDTO> student = new ArrayList<>();
student.add(new StudentDTO("요다2", 10, 99, 80));
student.add(new StudentDTO("만두3", 12, 90, 85));
student.add(new StudentDTO("건빵4", 13, 80, 75));
sample.printFilterMethod(student);
}
public void printFilterMethod(List<StudentDTO> list) {
// 80점이 넘는 학생만 반환해보자
list.stream().filter(x -> x.getScoreEnglish() >= 80).forEach(student -> System.out.println(student.getName()));
}
}
결과 :
요다2
만두3
나머지 Stream 메소드
sorted(compator) : 데이터 정렬
toArray(array-factory) : 배열로 변환
any / all / noneMatch : 일치하는 것을 찾음
findFirst / Any : 맨 처음이나 순서와 상관없는 것을 찾음
reduce / reduce : 결과를 취합
collect : 원하는 타입으로 데이터를 리턴
중간 연산의 종류
filter()map() / mapToInt() / mapToLong() / mapToDouble()flatMap() / flatMapToInt() / flatMapToLong() / flatMapToDouble()ditinct()sorted()peek()limit()skip()
종단 연산의 종류
forEach() / forEachOrdered()toArray()reduce()collect()min() / max() / count()anyMatch() / allMatch() / noneMatch()findFirst() / findAny()
'JAVA' 카테고리의 다른 글
| Optional 더 잘 사용해보기 (0) | 2023.04.10 |
|---|---|
| sigton Patten이란? (0) | 2023.03.31 |
| Garbeage Collection 이란? (0) | 2023.03.31 |
| JAVA 동작원리 그리고 JVM (0) | 2023.03.30 |
| Comparable 과 Comparator 차이점 (0) | 2023.03.30 |