[JAVA] Stream

펭귄안녕·2024년 10월 24일

JAVA

목록 보기
9/9
post-thumbnail

1. filter(), sum()

: 정수가 저장된 배열에서 짝수의 합을 출력

int[] arr={1,2,3,4,5};

기존 방식

int sum = 0;

for (int e : arr){
	if (e%2==0){
	}
}

System.out.println(sum);

스트림 방식

int result = Arrays.stream(arr) // 배열을 스트림화한 것
                .filter( num-> num%2==0 ) // 중간 연산
                .sum(); // 최종 연산

System.out.println(result);

Predicate< T> -> boolean x(T t)
IntPredicate< T> -> boolean x(int t)

  • 스트림의 마지막은 항상 최종 연산 한 번으로 끝낸다.
  • 중간 연산은 필요시 여러개 연결 가능
  • 중간 연산끼리의 순서는 상관 없음
  • 중간 연산은 필요할 때만 사용, 최종 연산은 반드시 존재해야함

2.

: 스트림을 사용하여 아래에 주어진 배열에서 짝수이면서 5보다 큰 데이터의 합을 출력

int[] arr2={2,6,10,1,7,3};

int result2= Arrays.stream(arr2)
                .filter( num -> num%2==0 )
                .filter( num -> num>5 )
                .sum();

System.out.println(result2);

3. forEach()

:

public static void main(String[] args) {
        List<Student> list = new ArrayList<>();

        list.add(new Student("고길동",20));
        list.add(new Student("장길산",100));
        list.add(new Student("박희동",50));

// 스트림을 사용해서 list에 저장된 학생 중 점수가 80점 이상인 학생만 걸러내는 코드 작성
        list.stream().filter(a-> a.getScore()>=80 ).forEach(s-> System.out.println(s));



    }

4. map(), mapToInt()

Arrays.asList / map()

public static void main(String[] args) {

	//list.add 말고도 추가 가능 
	List<String> list = Arrays.asList("떡볶이","주먹밥","치킨","콜라","치킨무");

	list.stream().map( str -> str.length() ) // 3,3,2,2,3
                .forEach(a-> System.out.println(a));

    }

map은 integer라서 sum으로 못 받음

mapToInt()

list.stream().mapToInt( str -> str.length() ) // int apply(T t)
                .sum(); // int만 호출 가능

5.

public static void main(String[] args) {

	List<Student> list = new ArrayList<>();
	list.add(new Student("황시목",50));
    list.add(new Student("한여진",80));
    list.add(new Student("최빛",70));
    list.add(new Student("서동재",20));
    list.add(new Student("강원철",100));

// 스트림을 사용해서 list에 저장된 학생 중 이름이 3글자이상인 이상인 학생의 점수의 합을 출력
	int sumOfScore = list.stream()
                .filter(stu -> stu.getName().length()>=3)
                .mapToInt(stu->stu.getScore())
                .sum();

	System.out.println(sumOfScore);
}

250 출력됨

6. collect()

:중간 연산의 결과로 나오는 데이터를 리스트 형태로 저장하는 최종 연산

// 점수가 50 초과인 것만
List<Student> s = list.stream().filter(stu->stu.getScore()>50)
                .collect(Collectors.toList());

이해못했음

7. average(), min(), max()

: 리턴타입 OptionalInt : average(), min(), max()

public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1,2,3,4,5);

        int sum =list.stream().mapToInt(num->num) // int x(T t) => Integer에서 int로 바꾸기
                .sum();
        long count = list.stream().mapToInt(num->num).count();


        OptionalInt min = list.stream().mapToInt(num->num).min();

        System.out.println(min.getAsInt()); // 데이터 없으면 오류남
        min.ifPresent( num -> System.out.println(num) );

    }

min만 입력해서 출력하면 OptionalInt[1] 이렇게 출력됨

8. reduce()

Function< T> -> R apply(T t)
BinaryFunction< T> -> R apply(T t,T t)
Operator< T> -> T x(T t)
BinaryOperator< T> -> T x(T t,T t)

public static void main(String[] args) {
        List<String> list = Arrays.asList("황시목","한여진","최빛","서부지검");

        String data = list.stream()
                .reduce("",(a,b)-> a.length() > b.length() ? a : b );
                // reduce 첫번째 매개변수 : list의 0번째 요소 추가
                

        System.out.println(data);



    }

전혀 모르겠음

...

: 매개변수로 문자열이 몇개 들어올지 불확실 => ...

public static void printAll(String... s){
	for (String e : s){
    	System.out.println(e);
        }
    // 위와 같은 코드 
    Arrays.stream(s).forEach(a-> System.out.println(a));
        
    }

}
printAll("김","수","한","무","두루미","와","거북이");

🤨

중간 연산 : filter(), map(), mapToInt()
최종 연산 : sum(), forEach(), collect(), count(), reduce(), [average(), min(), max()]

+)
다른 연산자 참고

0개의 댓글