Home>

I am writing various things about studying the Stream API.
Consider the following code as a methodappend ()that connects twoint []and returns a newint []It was.

static int [] append (int [] array1, int [] array2) {
    List<Integer>list = Arrays.stream (array1) .boxed (). Collect (Collectors.toList ());
    list.addAll (Arrays.stream (array2) .boxed (). collect (Collectors.toList ()));
    return list.stream (). mapToInt (Integer :: intValue) .toArray ();
  }


Although it is caused by sticking toarrayasarray->list->array, it looks somewhat redundant.
We would appreciate it if you could point out other improvements such as good practices.

  • Answer # 1

    You can write like this.

    import java.util. *;
    import java.util.stream. *;
    class Main {
        static int [] concat (int [] arr1, int [] arr2) {
            return IntStream.concat (
                IntStream.of (arr1), IntStream.of (arr2)
            ) .toArray ();
        }
        public static void main (String [] args) {
            System.out.println (Arrays.toString (
                concat (new int [] {1, 2, 3}, new int [] {4, 5, 6})
            ));
        }
    }

    ResultsWandbox

    [1, 2, 3, 4, 5, 6]
    Scheme 2

    It's a little difficult to read, but it can handle any number of joins.

    import java.util. *;
    import java.util.stream. *;
    class Main {
        static int [] concat (int [] ... arrs) {
            return Stream.of (arrs) .flatMapToInt (IntStream :: of) .toArray ();
        }
        public static void main (String [] args) {
            System.out.println (Arrays.toString (
                concat (new int [] {1, 2, 3}, new int [] {4, 5, 6}, new int [] {7, 8, 9})
            ));
        }
    }

    ResultsWandbox

    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    Reference

    The official reference for stability.

    Stream (Java SE 13&JDK 13)

    IntStream (Java SE 13&JDK 13)