외부 반복자(external iterator)는 개발자가 코드로 직접 Collection의 요소를 반복해서 가져오는 패턴을 말한다. for문, Iterator를 이용하는 whlie문 모두 외부 반복자를 이용하는 것이다.
내부 반복자(internal iterator)는 Collection 내부에서 요소들을 반복시키고, 개발자는 요소당 처리해야할 코드만 제공하는 패턴을 말한다. 내부 반복자를 사용해 개발자는 요소 처리 코드에만 집중할 수 있으며, 내부 반복자는 병렬 작업을 할 수 있도록 도와주기 때문에 효율적으로 요소를 반복시킬 수 있다. 스트림을 이용하면 코드도 간결해지지만, 요소의 병렬 처리가 Collecton 내부에서 처리되는것이 더 좋은 효과를 가져온다.
rangeClosed는 두번째 인자를 포함하며, range는 두번째 인자를 포함하지 않는다.
File Stream
Pipeline
대량의 데이터를 가공해 축소하는 것을 일반적으로 Reduction이라고 한다. 데이터의 합계, 평균값, 카운팅, 최대, 최소값 등이 대표적인 리덕션의 결과물이라고 볼 수 있다. 이때 결과물로 바로 집계할 수 없는 경우에는 중간처리(필터링, 매핑, 정렬, 그룹핑)이 필요하다.
파이프라인은 여러개의 스트림이 연결되어 있는 구조를 말하며, 최종처리를 제외하고는 모두 중간 처리 스트림이다.
class Driver {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,5,6);
Iterator<Integer> iter = list.iterator();
// 순서대로 1 2 3 4 5 6 출력
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
}
class Driver {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,5,6);
// Integer 데이터를 갖는 Stream 생성
Stream<Integer> stream = list.stream();
// forEach()를 사용해서 1 2 3 4 5 6 출력
stream.forEach((Integer i) -> { System.out.println(i); });
}
}
public class PracticeExample{
public static void main(String[] args){
List<String> list = Arrays.asList("Faker", "Teddy", "Effort", "Wolf", "Bang", "Clid");
Stream<String> stream = list.parallelStream(); // parallesStream : 병렬처리
stream.forEach(PracticeExample :: print);
}
public static void print(String str) {
System.out.println(str + Thread.currentThread().getName());
}
}
double avg = list.stream()
.mapToInt(Integer::intValue)
.average()
.orElse(0.0); // 값이 저장되지 않을 경우 defulat 0.0
list.stream()
.mapToInt(Integer::intValue)
.average()
.ifPresent(a -> System.out.println(a)); // 값이 존재하면 출력
int sum = sutentList.stream()
.map(Student :: getScore)
.reduce((a,b) -> a+b)
.get();
int sum = sutentList.stream()
.map(Student :: getScore)
.reduce(0, (a,b) -> a+b); // default 0