[백준BOJ] 소트인사이드 1427번 - string배열을 int[] 혹은 Integer[] 로 변환

백준 소트인사이드 1427번

단순히 역순으로 정렬하는 문제이다. 

1427번 해설
package solv.BOJ.sorting;

import java.io.*;
import java.util.*;

public class 소트인사이드1427 {
  static int[] arr;
  public static void main(String[] args) throws IOException{

    input();


  }
  private static void input() throws IOException{
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

    Integer[] arr = Arrays.stream(bf.readLine().split(""))
            .mapToInt(Integer::parseInt)
            .boxed()
            .toArray(Integer[]::new);



    Arrays.sort(arr, new Comparator<>(){

      @Override
      public int compare(Integer o1, Integer o2) {
        return o2 - o1;
      }
    });

    for (int i = 0 ; i  < arr.length ;i++){
      System.out.print(arr[i]);
    }

  }
}

 

이 글에서는 

String값을 int[] 혹은 Integer[]로 바꾸는 걸 한번 정리하고 넘어가려 한다.

우선 String 값은 

"12409" 혹은

"1 3 10 9 8" 혹은

"1
3
4
18
10" 이렇게 주어질 수 있으니 각 경우에 수에 대해서 보자.


String 값이 "12409" 와 같이 연속해서 주어진 경우

- char[] 로 반환

  • tocharArray() 사용
String str = "12345";

char[] arr = str.tocharArray(); //char형 배열 생성
  • charAt() 사용
    • toCharArray()에 비해 처리 속도가 내부적으로 빨라 문자열을 나눌때 사용하기 좋음
String str = "12345";
char[] arr = new char[str.length()];
for (int i = 0 ;  i < str.length(); i++){
	arr[i] = str.charAt(i);
}

 

- int[] 로 변환

  • stream 사용
int[] arr = Arrays.stream(bf.readLine().split(""))
            .mapToInt(Integer::parseInt)
            .toArray();

 

String 값이 "1 3 10 9 8"와 같이 주어진 경우
  • stream 이용
int[] arr = Arrays.stream(bf.readLine().split(" "))
            .mapToInt(Integer::parseInt)
            .toArray();

 

- Integer[] 로 변환

  • stream 이용
Integer[] arr = Arrays.stream(bf.readLine().split(""))
            .mapToInt(Integer::parseInt)
            .boxed()
            .toArray(Integer[]::new);

여기서 boxed는 IntStream 과 같이 원시 타입에 대한 스트림 자원을

클래스 타입 (예 : IntStream -> Stream<Integer>) 로 전환해준다.

** List 형태로 반환할 경우 아래와 같이 사용

var peopleName = people.stream()
                        .map(Person::name)
                        .collect(Collectors.toList());

var peopleName = people.stream()
                        .map(Person::name)
                        .toList();