Iterator와 비슷한 반복자,

차이점

  1. 내부 반복자 이므로 처리 속도가 빠르고 병렬 처리에 효율적
  2. 람다식으로 다양한 요소 처리를 정의 할 수 있음
  3. 중간 처리와 최종 처리를 수행하도록 파이프 라인을 형성할 수 있음
import java.sql.SQLOutput;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;

public class Test3 {
    public static void main(String[] args) {

        Set<String> set = new HashSet<>();
        set.add("aa");
        set.add("bb");
        set.add("cc");

        Stream<String> stream = set.stream();
        ((Stream<?>) stream).forEach(name-> System.out.println(name));
        // -> << 람다식
        // void b(String a) { sout(a); }

    }
}

중간처리와 최종처리(스트림 파이프라인)

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

class Student {
    private String name;
    private int score;

    public Student (String name, int score){
        this.name=name; this.score=score;
    }

    public String getName() { return name; }
    public int getScore() { return score;}
}

public class Test4 {
    public static void main(String[] args) {

       List<Student> list = Arrays.asList(
               new Student("홍길동", 10),
               new Student("김길동", 20),
               new Student("이길동", 30)
       );

       double avg = list.stream()
               .mapToInt(student -> student.getScore())
               .average()
               .getAsDouble();

        System.out.println("평균 점수: "+ avg);

    }
}

컬렉션으로부터 스트림 얻기

import ref.ex.ProductOrder;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

class Product{
    private int pno;
    private String name;
    private String company;
    private int price;

    public Product(int pno, String name, String company, int price){
        this.pno = pno;
        this.name = name;
        this.company = company;
        this.price = price;
    }

    public int getPho() { return pno; }
    public String getName() {return name;}
    public String getCompany() {return company;}
    public int getPrice(){return price;}

    @Override
    public String toString() {
        return new StringBuilder()
                .append("{")
                .append("pno:"+pno+",")
                .append("name:"+name+",")
                .append("company:"+company+",")
                .append("price:"+price)
                .append("}")
                .toString();

    }
}

public class Test5 {
    public static void main(String[] args) {

        List<Product> list = new ArrayList<>();
        for (int i = 1; i < 5; i++) {
        Product product = new Product(i, "상품+i", "멋진 회사", (int) (10000 * Math.random()));
        list.add(product);
    }
        Stream<Product> stream = list.stream();
        stream.forEach(p->System.out.println(p));
    }
}

요소를 하나씩 처리( 루핑)

→ 스트림에서 요소를 하나씩 반복해서 가져와 처리하는 것