본문 바로가기
JAVA/Coding Test

[JAVA] Stream과 Collection 시간 차이

by 주연이가 주연이다. 2024. 1. 18.

[참고] 백준 1181번 : 단어 정렬

 

배열의 중복을 제거할 때 Collection이 빠를까 Stream()이 빠를까 궁금했다. 

- Hash 사용

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;

public class P1181_단어정렬_hash {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine());

        String[] arr = new String[N];
        for (int i = 0; i < N; i++) {
            arr[i] = br.readLine();
        }
        //시작
        long start = System.currentTimeMillis();

        HashSet<String> hash = new HashSet<>();
        for (String s : hash) {
            hash.add(s);
        }



        String[] array = hash.toArray(String[]::new);

        //(String s1) -> s1.length() == String::length
        Arrays.sort(array, Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
/*        String[] array = Arrays.stream(arr).distinct().toArray(String[]::new);
                                                            //value -> new String[value] == String[]::new*/


        //끝
        long end = System.currentTimeMillis();

        for (String s : array) {
            System.out.println(s);
        }

        System.out.println("걸린 시간 : " + (end - start));

    }
}

 

- Stream 사용

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

public class P1181_단어정렬_stream {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine());

        String[] arr = new String[N];
        for (int i = 0; i < N; i++) {
            arr[i] = br.readLine();
        }

        //시작
        long start = System.currentTimeMillis();


        //(String s1) -> s1.length() == String::length
        Arrays.sort(arr, Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
        String[] array = Arrays.stream(arr).distinct().toArray(String[]::new);
                                                            //value -> new String[value] == String[]::new


        //끝
        long end = System.currentTimeMillis();

        for (String s : array) {
            System.out.println(s);
        }

        System.out.println("걸린 시간 : " + (end - start));

    }
}

Stream 사용
Collection 사용

 

 

[결론]

Stream보다 Collection이 더 빠르다.

728x90
반응형