Programing

Java 8 스트림을 배열로 변환하는 방법은 무엇입니까?

crosscheck 2020. 9. 30. 08:43
반응형

Java 8 스트림을 배열로 변환하는 방법은 무엇입니까?


Java 8 Stream을 배열로 변환하는 가장 쉽고 짧은 방법은 무엇입니까 ?


가장 쉬운 방법은 toArray(IntFunction<A[]> generator)배열 생성자 참조와 함께 메서드 를 사용하는 것입니다. 이것은 메소드 에 대한 API 문서 에서 제안됩니다 .

String[] stringArray = stringStream.toArray(String[]::new);

그것이하는 일은 정수 (크기)를 인수로 받아들이고 String[]정확히 (오버로드 중 하나)가하는 일인를 반환하는 메서드를 찾는 것입니다 new String[].

직접 작성할 수도 있습니다 IntFunction.

Stream<String> stringStream = ...;
String[] stringArray = stringStream.toArray(size -> new String[size]);

의 목적은 IntFunction<A[]> generator배열의 크기 인 정수를 새 배열로 변환하는 것입니다.

예제 코드 :

Stream<String> stringStream = Stream.of("a", "b", "c");
String[] stringArray = stringStream.toArray(size -> new String[size]);
Arrays.stream(stringArray).forEach(System.out::println);

인쇄물:

a
b
c

Stream에서 1에서 10까지의 값을 가진 int 배열을 얻으려면 IntStream이 있습니다.

여기에서 Stream.of 메서드를 사용하여 Stream을 만들고 mapToInt를 사용하여 Stream을 IntStream으로 변환합니다. 그런 다음 IntStream의 toArray 메서드를 호출 할 수 있습니다.

Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9,10);
//or use this to create our stream 
//Stream<Integer> stream = IntStream.rangeClosed(1, 10).boxed();
int[] array =  stream.mapToInt(x -> x).toArray();

다음은 IntStream 만 사용하여 Stream없이 동일한 것입니다.

int[]array2 =  IntStream.rangeClosed(1, 10).toArray();

이 간단한 코드 블록을 사용하여 Java 8 스트림을 배열로 변환 할 수 있습니다.

 String[] myNewArray3 = myNewStream.toArray(String[]::new);

하지만 더 자세히 설명하겠습니다. 먼저 세 가지 값으로 채워진 문자열 목록을 만들어 보겠습니다.

String[] stringList = {"Bachiri","Taoufiq","Abderrahman"};

주어진 Array에서 스트림을 만듭니다.

Stream<String> stringStream = Arrays.stream(stringList);

이제이 스트림에서 몇 가지 작업을 수행 할 수 있습니다.

Stream<String> myNewStream = stringStream.map(s -> s.toUpperCase());

마지막으로 다음 방법을 사용하여 Java 8 Array로 변환하십시오.

1-Classic 방법 (기능적 인터페이스)

IntFunction<String[]> intFunction = new IntFunction<String[]>() {
    @Override
    public String[] apply(int value) {
        return new String[value];
    }
};


String[] myNewArray = myNewStream.toArray(intFunction);

2-람다 식

 String[] myNewArray2 = myNewStream.toArray(value -> new String[value]);

3- 방법 참조

String[] myNewArray3 = myNewStream.toArray(String[]::new);

방법 참조 설명 :

이것은 다른 것과 엄격하게 동등한 람다 식을 작성하는 또 다른 방법입니다.


각 값을 쉼표로 구분하는 문자열 배열로 텍스트를 변환하고 모든 필드를 트리밍합니다. 예를 들면 다음과 같습니다.

String[] stringArray = Arrays.stream(line.split(",")).map(String::trim).toArray(String[]::new);

You can create a custom collector that convert a stream to array.

public static <T> Collector<T, ?, T[]> toArray( IntFunction<T[]> converter )
{
    return Collectors.collectingAndThen( 
                  Collectors.toList(), 
                  list ->list.toArray( converter.apply( list.size() ) ) );
}

and a quick use

List<String> input = Arrays.asList( ..... );

String[] result = input.stream().
         .collect( CustomCollectors.**toArray**( String[]::new ) );

Using the toArray(IntFunction<A[]> generator) method is indeed a very elegant and safe way to convert (or more correctly, collect) a Stream into an array of the same type of the Stream.

However, if the returned array's type is not important, simply using the toArray() method is both easier and shorter. For example:

    Stream<Object> args = Stream.of(BigDecimal.ONE, "Two", 3);
    System.out.printf("%s, %s, %s!", args.toArray());

Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);

int[] arr=   stream.mapToInt(x->x.intValue()).toArray();

     Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);

     Integer[] integers = stream.toArray(it->new Integer[it]);

You can do it in a few ways.All the ways are technically the same but using Lambda would simplify some of the code. Lets say we initialize a List first with String, call it persons.

List<String> persons = new ArrayList<String>(){{add("a"); add("b"); add("c");}};
Stream<String> stream = persons.stream();

Now you can use either of the following ways.

  1. Using the Lambda Expresiion to create a new StringArray with defined size.

    String[] stringArray = stream.toArray(size->new String[size]);

  2. Using the method reference directly.

    String[] stringArray = stream.toArray(String[]::new);

참고URL : https://stackoverflow.com/questions/23079003/how-to-convert-a-java-8-stream-to-an-array

반응형