Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[모던 자바 인 액션] 3주차 #5

Open
so3500 opened this issue Jul 7, 2023 · 1 comment
Open

[모던 자바 인 액션] 3주차 #5

so3500 opened this issue Jul 7, 2023 · 1 comment
Assignees
Labels
SummerCoding 땅울림 여름코딩 스터디 모던 자바 인 액션

Comments

@so3500
Copy link
Contributor

so3500 commented Jul 7, 2023

스터디 날짜

2023.07.13 목 20-21

내용

챕터5. 스트림 활용
챕터6. 스트림으로 데이터 수집

공유

최승위

이성온

정민교

@so3500 so3500 added SummerCoding 땅울림 여름코딩 스터디 모던 자바 인 액션 labels Jul 7, 2023
@so3500
Copy link
Contributor Author

so3500 commented Jul 13, 2023

import static org.assertj.core.api.AssertionsForClassTypes.*;

import java.util.stream.Stream;

import org.junit.jupiter.api.Test;

class StreamReduceTest {

	@Test
	void reduceSum() {
		Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

		// 0 + 1 + 2 + 3 + 4 + ... + 10
		Integer sum = numbers.reduce(0, (total, n) -> total + n); // Integer::sum

		assertThat(sum).isEqualTo(55);
	}

	@Test
	void reduceMinus() {
		Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

		// 0 - 1 - 2 - 3 - 4 - ... - 10
		Integer sum = numbers.reduce(0, (total, n) -> total - n);

		assertThat(sum).isEqualTo(-55);
	}

	@Test
	void reduceSumParallel() {
		Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

		// 0 + (1 + 2) + (3 + 4) + ... + (9 + 10)
		Integer sum = numbers.parallel().reduce(0, (total, n) -> total + n); // Integer::sum

		assertThat(sum).isEqualTo(55);
	}

	@Test
	void reduceMinusParallel() {
		Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

		// 0 - (1 - 2) - (3 - 4) - ... - (9 - 10)
		Integer sum = numbers.parallel().reduce(0, (total, n) -> total - n);

		assertThat(sum).isEqualTo(-5); // -55
	}

	@Test
	void reduceMinusParallelCombine() {
		Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

		// 0 - 1 - 2 - 3 - 4 - ... - 10
		// 첫번째 연산의 결과가 다음 연산에 영향을 주기 때문에 나눠서 작업을 처리할 수 없게됨
		Integer sum = numbers.parallel().reduce(0,
			(total, n) -> total - n,
			(total1, total2) -> total1 + total2); // Integer::sum / 병렬 처리된 결과들의 관계를 설정함

		assertThat(sum).isEqualTo(-55);
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
SummerCoding 땅울림 여름코딩 스터디 모던 자바 인 액션
Projects
None yet
Development

No branches or pull requests

3 participants