Stream
포스트
취소

Stream

알고리즘 문제를 풀면서 Java8 로 변형

count

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Basic
  int result = 0;

  for (int i = N+1; i <= N * 2; i++) {
    if (isPrime[i] == true) result++;
  }

  System.out.println(result);

// Java8
  System.out.println(IntStream.rangeClosed(N + 1, N * 2)
          .filter(x -> isPrime[x] == true)
          .count());


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  boolean[] isPrime = new boolean[MAX_N * 2 + 1];
  Arrays.fill(isPrime, true);
  isPrime[0] = false;
  isPrime[1] = false;

// Basic
  for (int i = 2; i <= MAX_N; i++) {
    if (isPrime[i] == true) {
      for (int j = i * 2; j <= MAX_N * 2; j += i) isPrime[j] = false;
    }
  }

// Java8
  IntStream.rangeClosed(2,MAX_N)
                .filter(i -> isPrime[i] == true)
                .forEach(i -> {
                    for(int j = i * 2; j <= MAX_N * 2; j += i) isPrime[j] = false;
                });

-> 에라토스테네스의 체는 낮은 소수부터 순차적으로 걸러야 한다.

Stream이 병렬처리면 사용할 수 없다.

parallelStream이 아닌 Stream은 순차적으로 수행한다.

   

성능 차이

1
2
3
4
5
6
7
8
// Basic - 6ms
  for (int j = 1; j <= num; j++) 
    isPrime[j] = false;


// Java8 - 183ms
  IntStream.rangeClosed(1, num)
                .forEach(x -> isPrime[x] = false);

for문에 비해 성능이 떨어짐.

알고리즘 풀 때 2중 Stream쓰면 느린게 체감됨.

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.

최소비용신장트리 - 프림, 크루스칼

다익스트라, 플로이드와샬 알고리즘

Comments powered by Disqus.