배열에서 스트리밍 할 때 정수를 문자열에 매핑 할 수없는 이유는 무엇입니까?
이 코드는 작동합니다 (Javadoc에서 가져옴).
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
String commaSeparatedNumbers = numbers.stream()
.map(i -> i.toString())
.collect(Collectors.joining(", "));
이것은 컴파일 할 수 없습니다.
int[] numbers = {1, 2, 3, 4};
String commaSeparatedNumbers = Arrays.stream(numbers)
.map((Integer i) -> i.toString())
.collect(Collectors.joining(", "));
IDEA는 "람다 식에 호환되지 않는 반환 유형 문자열"이 있다고 말합니다.
왜 ? 그리고 그것을 고치는 방법?
Arrays.stream(int[])
이 IntStream
아니라 Stream<Integer>
. 따라서을 객체에 매핑 할 때 mapToObj
대신 호출해야 합니다.map
int
예상대로 작동합니다.
String commaSeparatedNumbers = Arrays.stream(numbers)
.mapToObj(i -> ((Integer) i).toString()) //i is an int, not an Integer
.collect(Collectors.joining(", "));
다음과 같이 작성할 수도 있습니다.
String commaSeparatedNumbers = Arrays.stream(numbers)
.mapToObj(Integer::toString)
.collect(Collectors.joining(", "));
Arrays.stream(numbers)
를 생성 IntStream
후드와의지도 동작 IntStream
요구 IntUnaryOperator
(즉, 기능 int -> int
). 적용하려는 매핑 기능이이 계약을 따르지 않으므로 컴파일 오류가 발생합니다.
(이것이 반환됩니다) boxed()
를 얻으려면 전에 전화해야합니다 . 그런 다음 첫 번째 스 니펫에서했던 것처럼 호출 하십시오.Stream<Integer>
Arrays.asList(...).stream()
map
주 당신이 필요로하는 경우 그 boxed()
다음에 map
당신은 아마 사용하고자하는 mapToObj
직접.
장점은 개체에 mapToObj
각 int
값을 상자에 넣을 필요가 없다는 Integer
것입니다. 물론 적용하는 매핑 기능에 따라 그래서이 옵션은 쓰기도 더 짧습니다.
Arrays.stream (int [])을 사용하여 정수 스트림을 만들 수 있으며 다음 mapToObj
과 같이 호출 할 수 있습니다 mapToObj(Integer::toString)
.
String csn = Arrays.stream(numbers) // your numbers array
.mapToObj(Integer::toString)
.collect(Collectors.joining(", "));
도움이 되었기를 바랍니다..
이 샘플 및 질문의 목적이 문자열을 int 스트림에 매핑하는 방법을 찾는 것이라면 (예 : int 스트림을 사용하여 문자열 배열의 인덱스에 액세스) boxing을 사용하고 다음으로 캐스팅 할 수도 있습니다. int (그러면 배열의 인덱스에 액세스 할 수 있음).
int[] numbers = {0, 1, 2, 3};
String commaSeparatedNumbers = Arrays.stream(numbers)
.boxed()
.map((Integer i) -> Integer.toString((int)i))
.collect(Collectors.joining(", "));
.boxed () 호출은 IntStream (기본 int 스트림)을 Stream (객체 스트림, 즉 Integer 객체)으로 변환하여 다음에서 객체 (이 경우 String 객체)의 반환을 수락합니다. 당신의 람다. 여기에서는 데모 목적으로 숫자의 문자열 표현 일 뿐이지 만 이전에 언급 한 문자열 배열의 요소와 같이 모든 문자열 객체가 될 수 있습니다.
Just thought I'd offer another possibility. In programming, there are always multiple ways of accomplishing a task. Know as many as you can, then choose the one that fits the best for the task at hand, keeping in mind performance issues, intuitiveness, clarity of code, your preferences in coding style, and the most self-documenting.
Happy coding!
No boxing, AFAIK, and no explosion of little strings added to the heap:
public static void main(String[] args) {
IntStream stream = IntStream.of(1, 2, 3, 4, 5, 6);
String s = stream.collect(StringBuilder::new, (builder, n) -> builder.append(',').append(n), (x, y) -> x.append(',').append(y)).substring(1);
System.out.println(s);
}
'developer tip' 카테고리의 다른 글
JavaScript 또는 jQuery에서 HTML을 정규화하는 방법은 무엇입니까? (0) | 2020.09.22 |
---|---|
Rails 4에서 컨트롤러 또는 액션에 대한 X-Frame-Options를 재정의하는 방법 (0) | 2020.09.22 |
Makefile ifeq 논리적 또는 (0) | 2020.09.22 |
mkdir의 "-p"옵션 (0) | 2020.09.22 |
github markdown colspan (0) | 2020.09.22 |