Java 코테 참고 알게된 내용

LeeKyoungChang·2022년 10월 12일
0
post-thumbnail

📖 lambda식을 이용한 1차원 배열 정렬

일반적인 정렬을 할 때는 어떠한 자료형이든 상관없다.

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

Arrays.sort(arr);

// 1 2 3 4 순으로 결과 나온다.

Arrays.sort(arr, (a, b) ->  b- a);

// 할시, 오류가 발생한다.

 

역정렬을 할 때는 참조형 자료형을 사용해야 한다.

Integer[] arr = new Integer[5];
arr[0] = 1;
arr[1] = 2;
arr[3] = 4;

Arrays.sort(arr, (a, b) -> (b - a));

Integer[] intB = new Integer[B.length];

for(int i =0; i< B.length; i++){
    intB[i] = B[i];
}
  • 람다식을 사용

 

 

✔️ 특정 문자 개수 구하기

public class CharCount {
    public static void main(String[] args) {
        String str = "apple";
 
        System.out.println(countChar(str, 'a'));  // 1
        System.out.println(countChar(str, 'p'));  // 2
        System.out.println(countChar(str, 'l'));  // 1
        System.out.println(countChar(str, 'e'));  // 1
        System.out.println(countChar(str, 'c'));  // 0
 
    }
 
    public static int countChar(String str, char ch) {
        return str.length() - str.replace(String.valueOf(ch), "").length();
    }
}

 

profile
"야, (오류 만났어?) 너두 (해결) 할 수 있어"

0개의 댓글

관련 채용 정보