스트림 소개

반복자 스트림

List<String> list = Arrays.asList("a", "b", "c", "d", "e");

Iterator<String> iter = list.iterator();
while(iter.hasNext()) {
  System.out.println(iterator.next());
}

// same result
list.stream().forEach(System.out::println); // void forEach(Consumer<T> action)

스트림의 특징

람다식으로 요소 처리 코드를 제공

public class Item {
  private String name;
  private int cost;

  public Item (String name, int cost) {
    this.name = name;
    this.cost = cost;
  }

  public String getName() {return name;}
  public int getCost() {return cost;}
}

public class Example {
  public static void main(String[] args) {
    List<Item> list = Arrays.asList(new Item("car", 5000), new Item("computer", 1000));

    Stream<Item> stream = list.stream();
    stream.forEach(i -> {
      String name = i.getName();
      int cost = i.getCost();
      System.out.println(name + " " + cost);
    })
  }
}

내부 반복자를 사용해 병렬 처리가 쉬움

iterators
External & Internal Iterator
parallel
Parallel in Internal Iterator
public class Example {
  public static void main(String[] args) {
    List<String> list = Arrays.asList("a", "b", "c", "d", "e");

    // Sequential
    Stream<String> stream = list.stream();
    stream.forEach(Example::print);

    // Parallel
    Stream<String> pStream = list.parallelStream();
    pStream.forEach(Example::print);
  }

  public static void print(String str) {
    System.out.println(str + " " + Thread.currentThread().getName());
  }
}

중간 처리와 최종 처리를 할 수 있음

execute
중간 처리와 최종 처리
public class Example {
  public static void main(String[] args) {
    List<item> items = Arrays.asList(new Item("computer", 1000), new Item("car", 5000), new Item("cell phone", 300));

    double avg = items.stream()
      .mapToInt(Item::getCost) // 중간 처리 - 아이템 객체를 가격(int)으로 매핑
      .average() // 최종 처리 - 평균
      .getAsDouble();
  }
}

스트림의 종류

Stream<Object> stream = objecsList.stream(); // 컬렉션으로부터 스트림 획득

Stream<String> stream = Arrays.stream(strArray); // 배열(String[])으로부터 스트림 획득

IntStream stream = IntStream.rangeClosed(1, 100); // 숫자 범위(1 ~ 100까지의 정수)로부터 스트림 획득

// 파일로부터 스트림 획득
Path path = Paths.get("file path");
Files.lines(path, Charset.defaultCharSet())
  .forEach(System.out::println);

File file = path.toFile();
BufferedReader br = new BufferedReader(new FileReader(file));
br.lines().forEach(System.out::println);

// 디렉토리로부터 스트림 획득
Path path = Path.get("directory path");
Files.list(path)
  .forEach(p -> System.out.println(p.getFileName()));

스트림 파이프라인

중간 처리와 최종 처리

Stream<Member> maleFemaleStream = list.stream();
Stream<Member> maleStream = maleFemaleStream.filter(m -> m.getSex() == Member.MALE);
IntStream ageStream = maleStream.mapToInt(Member::getAge);
OptionalDouble optionalDouble = ageStream.average();
double ageAvg = optionalDouble.getAsDouble();

// same result
double ageAvg = list.stream() // 오리지널 스트림
  .filter(m -> m.getSex() == Member.MALE) // 중간 처리 스트림
  .mapToInt(Member::getAge) // 중간 처리 스트림
  .average() // 최종 처리
  .getAsDouble();