developer tip

배열에서 스트리밍 할 때 정수를 문자열에 매핑 할 수없는 이유는 무엇입니까?

optionbox 2020. 9. 22. 08:03
반응형

배열에서 스트리밍 할 때 정수를 문자열에 매핑 할 수없는 이유는 무엇입니까?


이 코드는 작동합니다 (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대신 호출해야 합니다.mapint

예상대로 작동합니다.

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직접.

장점은 개체에 mapToObjint값을 상자에 넣을 필요가 없다는 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);
}

참고URL : https://stackoverflow.com/questions/29028980/why-cant-i-map-integers-to-strings-when-streaming-from-an-array

반응형