ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JAVA_Stream
    JAVA 2020. 9. 3. 17:19
    반응형

    특징

    • data의 흐름 ( Java 8부터 사용 가능)
    • 람다식을 사용할 수 있다.
    • 함수적 인터페이스 이다.
    /*
    		Iterator 와 Stram 비교
    */
    
    List<String> fruits = Arrays.asList("apple","kiwi","banana","watermelon");
    
    Iterator<String> it = fruits.iterator();
    while(it.hasNext()){
    	System.out.println(it.next());
    }
    
    // 위에 Iterator 동일한 코드
    
    Stream<String> st = fruits.stream();
    st.forEach(fruit -> {
    	System.out.println(fruit);
    }); // Consumer
    

    종류

    • Stream

    String[] texts = {"김","이","박","최","정"};
    Stream<String> sstr = Arrays.stream(texts);
    sstr.forEach(s -> System.out.println(s + " " ));
    • IntStream

    int[] numbers = {100,99,89,95,81};
    IntStream istr = Arrays.stream(numbers);
    istr.forEach(n -> System.out.println(n + " "));
    
    // rangeClosed(시작값, 끝값) -> 범위로 부터 스트림 객체 생성
    public static int hap;
    public static void main(String[] args)
    {
    	IntStream ir = IntStream.rangeClosed(1,50);
    	ir.forEach(i -> hap = hap + i);
    }
    • LongStream
    • DoubleStream

    함수적 인터페이스

    • Consumer : 매개변수 있음, 리턴값 없음

    • Supplier : 매개변수 없음, 리턴값 있음

    • Function : 매개변수 있음, 리턴값 있음 (매개변수 Function 리턴)

    • Operator : 매개변수 있음, 리턴값 있음 (매개변수 Operator 리턴)

    • Predicate : 매개변수 있음, 리턴값이 boolean (매개변수 Predicate Boolean 리턴)

    IntSupplier dice = () -> {
    	int result = (int)(Math.random()*6)+1;
    	return result;	
    };
    System.out.println(dice.getAsInt);

    특징

    1. 람다식 또는 메서드 참조를 통한 원소 처리 코드를 매개값으로 전달
    // Fruit Class
    public Class Fruit {
    	 private String name;
    	 private int price;
    	 
    	public	Fruit(String name, int price){
    		this.name = name;
    		this.price = price;
    	}
    	
    	public String getName() { return name; }
    	public int getPrice() { return price; }
    	
    	
    }
    // main
    
    List<Fruit> fruits = Arrays.asList(new Fruit("apple",20000),new Fruit("kiwi",17000),
    					new Fruit("banana",10000),new Fruit("watermelon",25000));
    Stream<Fruit> st = fruits.stream();
    st.forEach(fruit -> {
    		String n = fruit.getName();
    		int p = fruit.getPrice();
    		System.out.println(n +" : "+ p +"원");
    });

    2. 병렬 처리가 쉽다.

    External( 외부반복자 ) → 시간이 오래걸린다

    Internal( 내부반복자 ) → 코드를 병렬로 처리한다.

    public class TestParallel{
    	public static void main(String[] args){
    		List<String> fruits = Arrays.asList("apple","kiwi","banana","watermelon");
    
    		Stream<String> st = fruits.stram();
    		Stream<String> paSt = fruits.parallelStream();
    		// 순차처리 -> Thread 이름이 전부 main으로 나온다.
    		st.forEach(fruit -> TestParallel.print(fruit));
    		// 병렬처리 -> 여러 Thread 이름이 찍힌다. 과일이 fruits에 담긴 순서대로 나오지 않는다.
    		paSt.forEach(fruit -> TestParallel.print(fruit));
    		// st.forEach(TestParallel::print);
    	}
    		public static void print(String f){
    			System.out.println(f + " : " + Thread.currentThread().getName());
    		}
    	
    }

    3. 중간 처리( filtering, sorting, mapping...etc), 최종 처리(합계, 평균, 세기....etc)가 가능 하다.

    중간처리

    • mapToInt

    List<Fruit> fruits = Arrays.asList(new Fruit("apple",20000),new Fruit("kiwi",17000),
    					new Fruit("banana",10000),new Fruit("watermelon",25000));
    
    // mapToInt -> "1","2","3" 을 가진 스트림이 있었으면 적용하면 1,2,3 을 가진 스트림으로 변환 해준다.
    int total = fruits.parallelStream().mapToInt(Fruit::getPrice).sum();
    double avg = fruits.parallelStream().mapToInt(Fruit::getPrice).average().getAsDouble();
    System.out.println("총 합계 : " + total);
    System.out.println("과일 가격 평균 : " + avg);
    • filtering ( distinct() → 매개 변수x, 중복 제거, filter(Predicate) → 조건 필터링 )

     

    List<String> city = Arrays.asList("서울","부산","광주","대구",
    "대전","부산","서울","인천","서울","경기");
    city.stream().distinct().forEach(c->System.out.println(c));
    // "서울","부산","광주","대구","대전","인천","경기"만 출력이 됨
    city.parallelStream().filter(c -> c.startsWith("대"))
    .forEach(c->System.out.println(c));
    // "대구","대전"만 출력이 됨
    
    • mapping( flatMapOOO(), MapOOO()) OOO → ToInt, ToDouble etc...

    List<String> il = Arrays.asList("홍 길동", "고 길동");
    il.stream().flatMap(words -> Arrays.stream(words.split(" ")))
    .forEach(word -> System.out.println(word));
    • sorted( )

    IntStream ist = Arrays.stream(new int[]{100,91,89,95,87});
    
    ist.sorted().forEach(n -> System.out.println(n));

    최종처리

    • sum

    int s = Arrays.stream(new int[] {9,22,7,71,16})
    .filter(n -> n%2 == 1)
    .sum().getAsInt();
    System.out.println(s);
    // 홀수를 다 합치면 87이기때문에 87 출력

     

    • average

    double d = Arrays.stream(new int[] {1,3,5,7,16})
    .filter(n -> n%2 == 1)
    .average().getAsInt();
    System.out.println(d);
    // 홀수를 모두 평균을 내면 4 이기때문에 4출력
    • max

    int max = Arrays.stream(new int[] {-9,22,7,71,16})
    .filter(n -> n%2 == 1)
    .max().getAsInt();
    System.out.println(max)
    // 홀수중 가장 큰값은 71 이기때문에 71출력
    • min

    int min = Arrays.stream(new int[] {9,22,7,71,16})
    .filter(n -> n%2 == 1)
    .min().getAsInt();
    System.out.println(min)
    // 홀수중 가장 작은값은 7 이기때문에 7출력
    • count

    long cnt = Arrays.stream(new int[] {9,22,7,71,16})
    .filter(n -> n%2 == 1)
    .count()
    System.out.println(cnt);
    // 홀수는 3개이기때문에 3출력
    • findFirst

    long f = Arrays.stream(new int[] {9,22,7,71,16})
    .filter(n -> n%2 == 1)
    .findFirst().getAsInt();
    System.out.println(f);
    // 홀수중 가장 첫번째 있는 숫자는 9 이기때문에 9출력
    • collect()

      스트림에서 요소들을 필터링 또는 매핑한 후 해당 요소들을 수집하는 최종 처리 메소드

      필요한 요소들만 컬렉션으로 담을 수 있다. 또한 요소들을 그룹핑한 후 집계 할 수 있다.

    List<Fruit> fruit = Arrays.asList(
                    new Fruit("apple", 20000),
                    new Fruit("kiwi", 17000),
                    new Fruit("banana", 11000),
                    new Fruit("watermelon", 25000)
            );
    
            List<Fruit> ExpensiveList = fruit.stream()
                    .filter(f -> f.getPrice() >= 20000)
                    .collect(Collectors.toList());
            ExpensiveList.forEach(System.out::println);
    반응형

    'JAVA' 카테고리의 다른 글

    JAVA_GUI  (0) 2020.09.03
    JAVA_Parallel Operation  (0) 2020.09.03
    JAVA_Collection  (0) 2020.09.03
    JAVA_Generic  (0) 2020.09.03
    JAVA_Exception  (0) 2020.09.03

    댓글

Designed by Tistory.