【解決方法】Java でオブジェクト型の配列を使用できますか?また、ストリーム API を使用してこの配列を平坦化するにはどうすればよいですか?

プログラミングQA


物体[] 配列 = { 1, 2, 新しいオブジェクト[]{ 3, 4, 新しいオブジェクト[]{ 5 }, 6, 7 };

整数[] flattenedArray = flatten(配列);
//私の関数 flatten(array) はオブジェクトを受け取ります[]inputArray を取得し、それをフラット化型の配列に返します
“`
public static 整数[] flatten(オブジェクト[] 入力配列) {
//操作を実行して整数を返す関数[]

}
“`

私が試したこと:

ストリームとして収集し、stream.toArray として返すようにしました。
Stream stream = Stream.of(inputArray);
stream= Arrays.stream(inputArray).flatMap(o->o instanceof Object[]? flatten((オブジェクト[])o): Stream.of(o));

解決策 1

はい、Java ではオブジェクト型の配列を使用できます。 Java の配列は、1 つの型の固定数の値を保持するコンテナーです。 配列の型は、Object などのオブジェクト型、またはその他のクラス型にすることができます。 たとえば、次のコードは、int、String、および別の Object 配列の 3 つの要素を含む Object 型の配列を作成します。

JavaScript
Object[] array = { 1, "Hello", new Object[]{ 3, 4, 5 } };

Stream API を使用してこの配列をフラット化するには、flatMap() メソッドを使用して配列内の各要素をストリームに変換し、すべてのストリームを 1 つのストリームに連結します。 その後、 toArray() メソッドを使用して、オブジェクトのストリームを目的の型の配列に変換できます。

オブジェクトの配列を平坦化するために flatten() メソッドを実装する方法の例を次に示します。

Java
<pre>public static Integer[] flatten(Object[] inputArray) {
    // Convert the input array into a stream of objects
    Stream<Object> stream = Arrays.stream(inputArray);

    // Recursively flatten the array by mapping each element to a stream
    // of objects, and then concatenating all the streams into a single stream
    stream = stream.flatMap(o -> o instanceof Object[] ? flatten((Object[])o) : Stream.of(o));

    // Convert the stream of objects into an array of integers
    Integer[] flattenedArray = stream.toArray(Integer[]::new);

    return flattenedArray;
}

その後、次のように flatten() メソッドを使用できます。

Object[] array = { 1, 2, new Object[]{ 3, 4, new Object[]{ 5 }, 6, 7 } };
Integer[] flattenedArray = flatten(array);

結果の flattenedArray は、次の要素を含む整数の配列になります。 [1, 2, 3, 4, 5, 6, 7].

コメント

タイトルとURLをコピーしました