프로그래머스 이어 붙인 수 (Stream 결과 String화)

박철현·2023년 5월 19일

프로그래머스

목록 보기
14/80

프로그래머스 - 이어 붙인 수

import java.util.Arrays;
import java.util.stream.Collectors;

class Solution {
    public int solution(int[] num_list) {
        String tmp_odd = Arrays.stream(num_list)
                .filter(a -> a%2 != 0)
                .mapToObj(a ->"" + a)
                .collect(Collectors.joining());

        String tmp_even = Arrays.stream(num_list)
        // 밑에 부분은 인텔리제이 추천! 메모리 절약할 수 있을듯
                .filter(a -> a%2 == 0)
                .mapToObj(a -> new StringBuilder().append("").append(a).toString())
                .collect(Collectors.joining());

        return Integer.parseInt(tmp_even) + Integer.parseInt(tmp_odd);
    }
}
  • 기존 : .toString()으로 마무리 -> 오류
    • toString()의 경우 스트림 객체의 문자열 표현 반환
import java.util.Arrays;
import java.util.stream.Collectors;
	public class Main {
    public static void main(String[] args) {
		
		int[] num_list = {1, 2, 3};
        String tmp_odd = Arrays.stream(num_list)
                .filter(a -> a%2 != 0)
                .mapToObj(a ->"" + a)
                .toString();

		System.out.println(tmp_odd);

    }
}
// 위 결과 : 스트림 객체의 문자열 표현
java.util.stream.IntPipeline$1@3f99bd52
  • 변경 : .collect(Collectors.joining())

    • 스트림 요소를 하나의 문자열로 반환
  • 스트림 toString() 과 .collect(Collectors.joining()) 차이를 알 수 있었음

  • 답으로 해결한 코드에서 a -> "" + a 보다는, a -> new StringBuilder().append("").append(a).toString() 으로 변경하는 것이 메모리를 덜 사용하기에 좋음! - 인텔리제이 짱!

profile
비슷한 어려움을 겪는 누군가에게 도움이 되길

0개의 댓글