[JAVA] 입력받은 문자열이 정수로 이루어져 있는지 확인

Jay_u·2023년 2월 5일
0

Java

목록 보기
7/8

입력받은 문자열에 정수만 포함되어있는지 확인하는 방법이 여러가지이지만
이번에 알게된 내용은 새로워서 글을 쓰게 되었다.
코드는 다음과 같다.


	private static void validateInt(String string) {
		if(!string.chars().allMatch(Charcter::isDigit)) {
			throw new IllegalArgumentException("정수만 입력가능합니다.");
		}
	}

String.chars().allMatch(Charcter::isDigit)

먼저 chars() 메소드는 공식문서에 다음과 같이 적혀있다.

default IntStream chars()
Returns a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted.
If the sequence is mutated while the stream is being read, the result is undefined

음 stream 형태로 char 값을 반환해주는거구나 그렇다면 문자열에 문자를 순차적으로 확인할 수 있겠다.

다음은 allMatch() 메소드이다.
Stream API에서 특정 조건을 만족하는 요소들을 얻을 수 있도로 매칭 메소드를 제공하는데
allMatch(), anyMatch(), noneMatch() 이다.
문자열의 모든 요소들이 주어진 조건에 만족하는지 확인하기 위해 allMatch()를 활용한다.

마지막으로 Character::isDigit 인데
더블콜론은 메소드 레퍼런스라고 하는데 이건 람다의 간결한 버전 중 하나라고 한다.
원래 람다식은 allMatch(x -> Character.isDigit(x))으로 사용하게 되지만
그냥 (Character::isDigit) 으로 더욱 간결하게 표현할 수 있는것이다.

profile
정확한 정보를 전달할려고 노력합니다.

0개의 댓글