코딩테스트 연습

woom·2023년 5월 1일
1

etc

목록 보기
1/3
post-thumbnail

📕 java Lv.0

🐣 01 ~ 04

1. 대소문자 바꿔서 출력

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        
        StringBuilder str = new StringBuilder();
        for(int i=0;i<a.length();i++){
            char c = a.charAt(i);
            if(Character.isUpperCase(c)){//대문자면
                str.append(Character.toLowerCase(c));//소문자로
            } else {
                str.append(Character.toUpperCase(c));
            }
        }
        System.out.print(str.toString());
    }
}

2. 문자열을 시계방향으로 90도 돌려서 출력

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        for (char ch : a.toCharArray())
            System.out.println(ch);
    }
}

3. 문자열 my_string, overwrite_string과 정수 s가 주어집니다. 문자열 my_string의 인덱스 s부터 overwrite_string의 길이만큼을 문자열 overwrite_string으로 바꾼 문자열을 return 하는 solution 함수를 작성해 주세요.

class Solution {
    public String solution(String my_string, String overwrite_string, int s) {
        return my_string.substring(0,s)
        +overwrite_string
        +my_string.substring(s+overwrite_string.length());
    }
}

4. 길이가 같은 두 문자열 str1과 str2가 주어집니다. 두 문자열의 각 문자가 앞에서부터 서로 번갈아가면서 한 번씩 등장하는 문자열을 만들어 return 하는 solution 함수를 완성해 주세요.

class Solution {
    public String solution(String str1, String str2) {
        StringBuilder sb = new StringBuilder();
        int len=str1.length();
        for(int i=0;i<len;i++){
            sb.append(str1.charAt(i)).append(str2.charAt(i));
        }
        return sb.toString();
    }    
}

🐣 05 ~ 09

5. 문자들이 담겨있는 배열 arr가 주어집니다. arr의 원소들을 순서대로 이어 붙인 문자열을 return 하는 solution함수를 작성해 주세요.

class Solution {
    public String solution(String[] arr) {
        String answer = "";
        for(String a : arr) {
            answer += a;
        }
        return answer;
    }
}

6. 연산 ⊕는 두 정수에 대한 연산으로 두 정수를 붙여서 쓴 값을 반환한다. 양의 정수 a와 b가 주어졌을 때, a ⊕ b와 b ⊕ a 중 더 큰 값을 return 하는 solution 함수를 완성해 주세요. (단, a ⊕ b와 b ⊕ a가 같다면 a ⊕ b를 return 합니다.)

class Solution {
    public int solution(int a, int b) {
        int answer = 0;
        int ab = Integer.parseInt(""+a+b);
        int ba = Integer.parseInt(""+b+a);
        
        if(ab>=ba){
            answer = ab;
        } else { 
            answer = ba;
        }
        return answer;
    }
}

7. 문자열에 따라 다음과 같이 두 수의 크기를 비교하려고 합니다. 두 수가 n과 m이라면 ">", "=" : n >= m, "<", "=" : n <= m, ">", "!" : n > m, "<", "!" : n < m. 두 문자열 ineq와 eq가 주어집니다. ineq는 "<"와 ">"중 하나고, eq는 "="와 "!"중 하나입니다. 그리고 두 정수 n과 m이 주어질 때, n과 m이 ineq와 eq의 조건에 맞으면 1을 아니면 0을 return하도록 solution 함수를 완성해주세요.

class Solution {
    public int solution(String ineq, String eq, int n, int m) {
        boolean answer = false;
        if (ineq.equals(">") && eq.equals("="))
            answer = n >= m;
        else if (ineq.equals("<") && eq.equals("="))
            answer = n <= m;
        else if (ineq.equals(">") && eq.equals("!"))
            answer = n > m;
        else 
            answer = n < m;
        return answer ? 1 : 0;
    }
}

8. 두 정수 a, b와 boolean 변수 flag가 매개변수로 주어질 때, flag가 true면 a + b를 false면 a - b를 return 하는 solution 함수를 작성해 주세요.

class Solution {
    public int solution(int a, int b, boolean flag) {
        if (flag){
            return a+b;
        } else {
            return a-b;
        }
    }
}

9. 1부터 6까지 숫자가 적힌 주사위가 세 개 있습니다. 세 주사위를 굴렸을 때 나온 숫자를 각각 a, b, c라고 했을 때 얻는 점수는 다음과 같습니다. 세 숫자가 모두 다르다면 a + b + c 점을 얻습니다. 세 숫자 중 어느 두 숫자는 같고 나머지 다른 숫자는 다르다면 (a + b + c) × (a2 + b2 + c2 )점을 얻습니다. 세 숫자가 모두 같다면 (a + b + c) × (a2 + b2 + c2 ) × (a3 + b3 + c3 )점을 얻습니다. 세 정수 a, b, c가 매개변수로 주어질 때, 얻는 점수를 return 하는 solution 함수를 작성해 주세요.

class Solution {
    public int solution(int a, int b, int c) {
        int answer = 0;
        
        if(a == b && b == c){
            answer = 27 * a*a*a*a*a*a;
        } else if (a == b || b == c || c == a){
            answer = (a+b+c)*(a*a+b*b+c*c);
        } else {
            answer = a+b+c;
        }
        return answer;
    }
}
다른 사람 풀이
class Solution {
    public int solution(int a, int b, int c) {
        int answer = 1;

        int count = 1;
        if(a == b || a == c || b == c) {
            count++;
        }
        if(a == b && b == c) {
            count++;
        }
        for(int i = 1; i <= count; i++) {
            answer *= (pow(a,i)+pow(b,i)+pow(c,i));
        }
        return answer;
    }

    private int pow(int a, int b) {
        if(b == 0) return 1;
        return a * pow(a, b-1);
    }
}

🐣 10 ~ 14

10. 두 정수 a, d와 길이가 n인 boolean 배열 included가 주어집니다. 첫째항이 a, 공차가 d인 등차수열에서 included[i]가 i + 1항을 의미할 때, 이 등차수열의 1항부터 n항까지 included가 true인 항들만 더한 값을 return 하는 solution 함수를 작성해 주세요.

class Solution {
    public int solution(int a, int d, boolean[] included) {
        int answer = 0;
        
        for(int i=0; i<included.length; i++){
            if(included[i]){
                answer += a+d*i;
            }            
        }
        return answer;
    }
}

11. 문자열 code가 주어집니다. code를 앞에서부터 읽으면서 만약 문자가 "1"이면 mode를 바꿉니다. mode에 따라 code를 읽어가면서 문자열 ret을 만들어냅니다. mode는 0과 1이 있으며, idx를 0 부터 code의 길이 - 1 까지 1씩 키워나가면서 code[idx]의 값에 따라 다음과 같이 행동합니다. mode가 0일 때 code[idx]가 "1"이 아니면 idx가 짝수일 때만 ret의 code[idx]를 추가합니다. code[idx]가 "1"이면 mode를 0에서 1로 바꿉니다. mode가 1일 때 code[idx]가 "1"이 아니면 idx가 홀수일 때만 ret의 맨 뒤에 code[idx]를 추가합니다. code[idx]가 "1"이면 mode를 1에서 0으로 바꿉니다. 문자열 code를 통해 만들어진 문자열 ret를 return 하는 solution 함수를 완성해 주세요. 단, 시작할 때 mode는 0이며, return 하려는 ret가 만약 빈 문자열이라면 대신 "EMPTY"를 return 합니다.

class Solution {
    public String solution(String code) {
        int mode=0;
        String answer="";
        for(int i=0; i<code.length(); i++){
            if(mode==0) {
                if(code.charAt(i)=='1' ){
                        mode=1;
                } else {
                    if(i%2==0){
                        answer += code.charAt(i);
                    }
                }
            } else if(mode==1){
                if(code.charAt(i)=='1' ){
                        mode=0;
                } else {
                    if(i%2==1){
                        answer += code.charAt(i);
                    }
                }
            }
        }
        if(answer.equals("")){
            answer = "EMPTY";
        }
        return answer;
    }
}

12. 정수가 담긴 리스트 num_list가 주어질 때, 모든 원소들의 곱이 모든 원소들의 합의 제곱보다 작으면 1을 크면 0을 return하도록 solution 함수를 완성해주세요.

class Solution {
    public int solution(int[] num_list) {
        int sum = 0;
        int mul = 1;
        for(int num : num_list){
            sum += num;
            mul *= num;
        }
        if(mul < sum*sum){
            return 1;
        } else {
            return 0;
        }
    }
}

13. 정수가 담긴 리스트 num_list가 주어집니다. num_list의 홀수만 순서대로 이어 붙인 수와 짝수만 순서대로 이어 붙인 수의 합을 return하도록 solution 함수를 완성해주세요.

class Solution {
    public int solution(int[] num_list) {
        String odd="";
        String even="";
        
        for(int i=0; i<num_list.length; i++){
            if(num_list[i]%2==0){
                even += num_list[i];
            } else {
                odd += num_list[i];
            }
        }
        return Integer.parseInt(odd) + Integer.parseInt(even);
    }
}

다른 사람 풀이
class Solution {
    public int solution(int[] num_list) {
        int answer = 0;

        int even = 0;
        int odd = 0;

        for(int num : num_list) {
            if(num % 2 == 0) {
                even *= 10;
                even += num;
            } else {
                odd *= 10;
                odd += num;
            }
        }
        answer = even + odd;

        return answer;
    }
}

14. 정수 리스트 num_list가 주어질 때, 마지막 원소가 그전 원소보다 크면 마지막 원소에서 그전 원소를 뺀 값을 마지막 원소가 그전 원소보다 크지 않다면 마지막 원소를 두 배한 값을 추가하여 return하도록 solution 함수를 완성해주세요.

class Solution {
    public int[] solution(int[] num_list) {
        int length = num_list.length;
        int[] result = new int[length+1];
        for(int i=0; i<length;i++ ){
            result[i]=num_list[i];
        }
        
        int last = num_list[length-1];
        int prev = num_list[length-2];
        
        if(prev >= last){
            result[length] = 2* last;
        } else {
            result[length] = last-prev;
        }
        return result;
    }
}

🐣 15 ~ 19

15. 정수 n과 문자열 control이 주어집니다. control은 "w", "a", "s", "d"의 4개의 문자로 이루어져 있으며, control의 앞에서부터 순서대로 문자에 따라 n의 값을 바꿉니다. "w" : n이 1 커집니다. "s" : n이 1 작아집니다. "d" : n이 10 커집니다. "a" : n이 10 작아집니다. 위 규칙에 따라 n을 바꿨을 때 가장 마지막에 나오는 n의 값을 return 하는 solution 함수를 완성해 주세요.

class Solution {
    public int solution(int n, String control) {
        char[] arr = control.toCharArray();
        for(int i=0; i<control.length(); i++){
            
            char a = arr[i];
            if(a=='w'){
                n+=1;
            } else if(a=='s'){
                n-=1;
            } else if(a=='d'){
                n+=10;
            } else if(a=='a'){
                n-=10;
            }
        }
        return n;
    }
}
다른사람풀이
class Solution {
    public int solution(int n, String control) {
        int answer = n;

        for(char ch : control.toCharArray()) {
            switch(ch) {
                case 'w': answer += 1; break;
                case 's': answer -= 1; break;
                case 'd': answer += 10; break;
                case 'a': answer -= 10; break;
                default:break;
            }
        }
        return answer;
    }
}

16. 정수 배열 numLog가 주어집니다. 처음에 numLog[0]에서 부터 시작해 "w", "a", "s", "d"로 이루어진 문자열을 입력으로 받아 순서대로 다음과 같은 조작을 했다고 합시다. "w" : 수에 1을 더한다. "s" : 수에 1을 뺀다. "d" : 수에 10을 더한다. "a" : 수에 10을 뺀다. 그리고 매번 조작을 할 때마다 결괏값을 기록한 정수 배열이 numLog입니다. 즉, numLog[i]는 numLog[0]로부터 총 i번의 조작을 가한 결과가 저장되어 있습니다. 주어진 정수 배열 numLog에 대해 조작을 위해 입력받은 문자열을 return 하는 solution 함수를 완성해 주세요.

class Solution {
    public String solution(int[] numLog) {
        String answer = "";
        int len = numLog.length;
        
        for(int i=1; i<len; i++){
            int num=numLog[i]-numLog[i-1];
            if (num == 1){
                answer += "w";
            } else if(num == -1){
                answer += "s";
            } else if(num == 10){
                answer += "d";
            } else if(num == -10){
                answer += "a";
            }
        }
        return answer;
    }
}

17. 정수 배열 arr와 2차원 정수 배열 queries이 주어집니다. queries의 원소는 각각 하나의 query를 나타내며, [i, j] 꼴입니다. 각 query마다 순서대로 arr[i]의 값과 arr[j]의 값을 서로 바꿉니다. 위 규칙에 따라 queries를 처리한 이후의 arr를 return 하는 solution 함수를 완성해 주세요.

class Solution {
    public int[] solution(int[] arr, int[][] queries) {

        for (int i = 0; i < queries.length; i++) {
            int temp = arr[queries[i][0]];
            arr[queries[i][0]] = arr[queries[i][1]];
            arr[queries[i][1]] = temp;
        }
        return arr;
    }    
}

18. 정수 배열 arr와 2차원 정수 배열 queries이 주어집니다. queries의 원소는 각각 하나의 query를 나타내며, [s, e, k] 꼴입니다. 각 query마다 순서대로 s ≤ i ≤ e인 모든 i에 대해 k보다 크면서 가장 작은 arr[i]를 찾습니다. 각 쿼리의 순서에 맞게 답을 저장한 배열을 반환하는 solution 함수를 완성해 주세요. 단, 특정 쿼리의 답이 존재하지 않으면 -1을 저장합니다.

import java.util.Arrays;

class Solution {
    public int[] solution(int[] arr, int[][] queries) {
        int[] answer = new int[queries.length];
        
        for (int i = 0; i < queries.length; i++) {
            int s = queries[i][0];
            int e = queries[i][1];
            int k = queries[i][2];
            int min = Integer.MAX_VALUE;
            boolean exist = false;
            
            for (int j = s; j <= e; j++) {
                if (arr[j] > k && arr[j] < min) {
                    min = arr[j];
                    exist = true;
                }
            }
            if (exist) {
                answer[i] = min;
            } else {
                answer[i] = -1;
            }
        }
        return answer;
    }
}
다른사람풀이
import java.util.Arrays;

class Solution {
    public int[] solution(int[] arr, int[][] queries) {

        int[] answer = new int[queries.length];
        Arrays.fill(answer, -1);//answer배열 -1로 초기화

        for (int idx = 0; idx < queries.length; idx++) {
            int[] query = queries[idx];
            int s = query[0], e = query[1], k = query[2];

            for (int i = s; i <= e; i++) {
                if (k < arr[i]) {
                    answer[idx] = answer[idx] == -1 ? arr[i] : Math.min(answer[idx], arr[i]);
                    //Math.min(a,b) a와 b 중 더 작은 값을 반환
                }
            }

        }

        return answer;
    }
}

19. 정수 l과 r이 주어졌을 때, l 이상 r이하의 정수 중에서 숫자 "0"과 "5"로만 이루어진 모든 정수를 오름차순으로 저장한 배열을 return 하는 solution 함수를 완성해 주세요. 만약 그러한 정수가 없다면, -1이 담긴 배열을 return 합니다.

import java.util.stream.IntStream;

class Solution {
    public int[] solution(int l, int r) {
        int[] answer = IntStream.rangeClosed(l, r).filter(i -> {
            while (i > 0) {
                if (i % 5 != 0) return false;
                i /= 10;
            }
            return true;
        }).toArray();

        return answer.length == 0 ? new int[]{-1} : answer;
    }
}

다른사람풀이

import java.util.ArrayList;

class Solution {
    public int[] solution(int l, int r) {

        ArrayList<Integer> list = new ArrayList<>();

        for (int i = 1; i < 64; i++) {
            int num = Integer.parseInt(Integer.toBinaryString(i)) * 5;
            //Integer.toBinaryString : 10진수 <-> 2진수 변환
            if (l <= num && num <= r)
                list.add(num);
        }

        return list.isEmpty() ? new int[] { -1 } : list.stream().mapToInt(i -> i).toArray();
        //리스트를 정수 배열로 변환
    }
}

🐣 20 ~ 24

20. 정수 start와 end가 주어질 때, start부터 end까지의 숫자를 차례로 담은 리스트를 return하도록 solution 함수를 완성해주세요.

import java.util.ArrayList;

class Solution {
    public int[] solution(int start, int end) {
        int[] result = new int[end-start+1];
        for(int i=start; i<=end; i++){
            result[i-start]=i;
        }
        return result;
    }
}

다른사람풀이

import java.util.stream.IntStream;

class Solution {
    public int[] solution(int start, int end) {
        return IntStream.rangeClosed(start, end).toArray();
    }
}

21. 모든 자연수 x에 대해서 현재 값이 x이면 x가 짝수일 때는 2로 나누고, x가 홀수일 때는 3 * x + 1로 바꾸는 계산을 계속해서 반복하면 언젠가는 반드시 x가 1이 되는지 묻는 문제를 콜라츠 문제라고 부릅니다. 그리고 위 과정에서 거쳐간 모든 수를 기록한 수열을 콜라츠 수열이라고 부릅니다. 계산 결과 1,000 보다 작거나 같은 수에 대해서는 전부 언젠가 1에 도달한다는 것이 알려져 있습니다. 임의의 1,000 보다 작거나 같은 양의 정수 n이 주어질 때 초기값이 n인 콜라츠 수열을 return 하는 solution 함수를 완성해 주세요.

import java.util.ArrayList;
import java.util.List;

class Solution {
    public int[] solution(int n) {
        List<Integer> list = new ArrayList<>();
        list.add(n);
        while(n!=1){
            if(n%2==0){
                n/=2;
            } else {
                n=3*n+1;
            }
            list.add(n);
        }
        int[] answer= new int[list.size()];//list를 int배열로 반환해야쥬
        for(int i=0; i<list.size();i++){
            answer[i]=list.get(i);
        }
        return answer;
    }
}

다른사람풀이

class Solution {
    public int[] solution(int n) {
        return IntStream.concat(//두 instream 붙여
                        IntStream.iterate(n, i -> i > 1, i -> i % 2 == 0 ? i / 2 : i * 3 + 1),
                        //n부터 시작하여, i가 1보다 작아질때까지 실행
                        IntStream.of(1))//1을 추가하는 instream생성
                .toArray();//int배열로반환
    }
}

22. 정수 배열 arr가 주어집니다. arr를 이용해 새로운 배열 stk를 만드려고 합니다. 변수 i를 만들어 초기값을 0으로 설정한 후 i가 arr의 길이보다 작으면 다음 작업을 반복합니다. 만약 stk가 빈 배열이라면 arr[i]를 stk에 추가하고 i에 1을 더합니다. stk에 원소가 있고, stk의 마지막 원소가 arr[i]보다 작으면 arr[i]를 stk의 뒤에 추가하고 i에 1을 더합니다. stk에 원소가 있는데 stk의 마지막 원소가 arr[i]보다 크거나 같으면 stk의 마지막 원소를 stk에서 제거합니다. 위 작업을 마친 후 만들어진 stk를 return 하는 solution 함수를 완성해 주세요.

import java.util.*;

class Solution {
    public int[] solution(int[] arr) {
         int[] stk = new int[arr.length];
        int i = 0;
        int top = -1;

        while (i < arr.length) {
            if (top == -1 || stk[top] < arr[i]) {
                stk[++top] = arr[i];
                i++;
            } else if (stk[top] >= arr[i]) {
                top--;
            }
        }

        return Arrays.copyOfRange(stk, 0, top + 1);
    }
}

다른사람풀이

import java.util.*;

class Solution {
    public Stack<Integer> solution(int[] arr) {
        Stack<Integer> stack = new Stack<>();
        int i = 0;

        while (i < arr.length) {
            if (stack.empty() || stack.peek() < arr[i]) {
                stack.push(arr[i]);
                i++;
            } else if (stack.peek() >= arr[i]) {
                stack.pop();
            }
        }
        return stack;
    }
}

23. 1부터 6까지 숫자가 적힌 주사위가 네 개 있습니다. 네 주사위를 굴렸을 때 나온 숫자에 따라 다음과 같은 점수를 얻습니다. 네 주사위에서 나온 숫자가 모두 p로 같다면 1111 × p점을 얻습니다. 세 주사위에서 나온 숫자가 p로 같고 나머지 다른 주사위에서 나온 숫자가 q(p ≠ q)라면 (10 × p + q)2 점을 얻습니다. 주사위가 두 개씩 같은 값이 나오고, 나온 숫자를 각각 p, q(p ≠ q)라고 한다면 (p + q) × |p - q|점을 얻습니다. 어느 두 주사위에서 나온 숫자가 p로 같고 나머지 두 주사위에서 나온 숫자가 각각 p와 다른 q, r(q ≠ r)이라면 q × r점을 얻습니다. 네 주사위에 적힌 숫자가 모두 다르다면 나온 숫자 중 가장 작은 숫자 만큼의 점수를 얻습니다. 네 주사위를 굴렸을 때 나온 숫자가 정수 매개변수 a, b, c, d로 주어질 때, 얻는 점수를 return 하는 solution 함수를 작성해 주세요.

class Solution {
    public int solution(int a, int b, int c, int d) {
        //모두 같을 때
        if (a==b && b==c && c==d) {
        return 1111 * a;
        } 
        //세 주사위가 같을 때
        else if (a==b && b==c)  {
        return (10 * a + d) * (10 * a + d);
        } 
        else if (a==d && d==c)  {
        return (10 * a + b) * (10 * a + b);
        }
        else if (a==b && b==d)  {
        return (10 * a + c) * (10 * a + c);
        }
        else if (d==b && b==c)  {
        return (10 * d + a) * (10 * d + a);
        }
        //두 주사위가 모두 같을 때
        else if ((a==b && c==d) || (a==c && b==d) || (a==d && b==c)) {
        int p = Math.max(Math.max(a, b), Math.max(c, d));
        int q = Math.min(Math.min(a, b), Math.min(c, d));
        return (p + q) * Math.abs(p - q);
        }
        //두 주사위가 같고 나머지 주사위가 각각 다를 때
        else if (a==b && c!=d) {
        return c * d;
        } else if (a==c && b!=d) {
        return b * d;
        } else if (a==d && b!=c) {
        return b * c;
        } else if (b==c && a!=d) {
        return a * d;
        } else if (b==d && a!=c) {
        return a * c;
        } else if (c==d && a!=b) {
        return a * b;
        } 
        //모두 다를 때
        else {
        return Math.min(Math.min(a, b), Math.min(c, d));
    	}
	}
}

다른사람풀이

import java.util.Arrays;

class Solution {
    public int solution(int a, int b, int c, int d) {

        int[] dice = { a, b, c, d };
        Arrays.sort(dice);

        int ans = 0;

        if (dice[0] == dice[3]) {
            ans = 1111 * dice[3];
        } else if (dice[0] == dice[2] || dice[1] == dice[3]) {
        //math.pow(a,b) : a의 b제곱
            ans = (int) Math.pow(dice[1] * 10 + (dice[0] + dice[3] - dice[1]), 2);
        } else if (dice[0] == dice[1] && dice[2] == dice[3]) {
            ans = (dice[0] + dice[3]) * (dice[3] - dice[0]);
        } else if (dice[0] == dice[1]) {
            ans = dice[2] * dice[3];
        } else if (dice[1] == dice[2]) {
            ans = dice[0] * dice[3];
        } else if (dice[2] == dice[3]) {
            ans = dice[0] * dice[1];
        } else {
            ans = dice[0];
        }

        return ans;
    }
}

24.


📌 참고

  • toArray

    • String.toCharArray() : String(문자열)을 char형 배열로 바꾼다.
    • List.toArray() : List 컨테이너의 인스턴스를 배열로 바꾼다
  • Stringbuilder : string과 문자열을 더할 때 새로운 객체를 생성하는 것이 아니라 기존의 데이터에 더하는 방식을 사용하여 속도가 빠르다.

    • StringBuilder sb = new StringBuilder();
           sb.append("a");
           sb.append("b");
           System.out.print(sb.toString());
    • 문자열을 출력할 때는 toString해야함
  • 문자열 형변환 (객체를 String 문자열 참조 자료형으로 형 변환하는 역할)

    • String.valueOf() : 전달받은 파라미터가 null이 전달될 경우 문자열 "null"을 반환
    • Object.toString() : null값을 문자열로 형 변환 시 NullPointerException를 발생
  • import java.util.Arrays;

    • Arrays.fill(배열 변수, 배열 데이터) : 배열의 값을 일괄 초기화
    • Arrays.copyOf(원본배열, 복사할 길이)
    • Arrays.copyOfRange(원본 배열, 복사할 시작인덱스, 복사할 끝인덱스)
  • stream : 컬렉션 데이터를 선언형으로 쉽게 처리

    • IntStream.rangeClosed(l, r) : l~r 까지의 숫자(정수스트림)를 차례대로 생성
    • IntStream.range(l, r) : : l~r-1 까지의 숫자를 차례대로 생성
      List<Integer> redHeavyAppleUid = appleList.stream()
           .filter(apple -> apple.getColor().equals("RED"))        // 빨간색 사과 필터링
           .sorted(Comparator.comparing(Apple::getWeight))         // 무게 순서대로 정렬
           .map(Apple::getUidNum).collect(Collectors.toList());    // 사과 고유번호 출력

profile
Study Log 📂

0개의 댓글