在Java中展开嵌套数组

13

我想要将嵌套的数组压平,例如:

[[[1],2],[3]],4] -> [1,2,3,4] 

在Java中手动操作,我完全找不到头绪! :S

我已经尝试了一份手动Java脚本指南,但没有得到解决方案。

public static void main(String[] args) {

  Object arr[] = { 1, 2, new Object[] { 4, new int[] { 5, 6 }, 7 }, 10 };
  String deepToString = Arrays.deepToString(arr);
  String replace = deepToString.replace("[", "").replace("]", "");
  String array[] = replace.split(",");
  int temp[] = new int[array.length];
  for (int i = 0; i < array.length; i++) {
    temp[i] = Integer.parseInt(array[i].trim());
  }
  System.out.println(Arrays.toString(temp));
}

6
这是一个 JavaScript 问题,在 Java 中没有意义。 - dotvav
我想用任何语言解决它,Java或JavaScript。 - mhGaber
我们真的很想帮忙,但是我个人并不理解你在询问什么。你能给一个Java示例,展示输入和期望输出吗? - Sharon Ben Asher
2
但在Java和JavaScript中解决这个问题的方法完全不同... - Michał Szydłowski
我已经编辑了问题以显示输入和输出,希望现在清楚了。 - mhGaber
显示剩余3条评论
9个回答

23

流(Stream) API提供了一种紧凑且灵活的解决方案。使用该方法

private static Stream<Object> flatten(Object[] array) {
    return Arrays.stream(array)
        .flatMap(o -> o instanceof Object[] a? flatten(a): Stream.of(o));
}

或在JDK 16之前

private static Stream<Object> flatten(Object[] array) {
    return Arrays.stream(array)
        .flatMap(o -> o instanceof Object[]? flatten((Object[])o): Stream.of(o));
}

您可以执行以下操作

Object[] array = { 1, 2, new Object[]{ 3, 4, new Object[]{ 5 }, 6, 7 }, 8, 9, 10 };
System.out.println("original: "+Arrays.deepToString(array));

Object[] flat = flatten(array).toArray();
System.out.println("flat:     "+Arrays.toString(flat));

或者当您假设叶子对象为特定类型时:

int[] flatInt = flatten(array).mapToInt(Integer.class::cast).toArray();
System.out.println("flat int: "+Arrays.toString(flatInt));

遗憾的是,如果内部数组是原始类型(如int[]),则此方法无法正常工作,因为“o instanceof Object []”检查失败,而原始数组无法转换为对象数组。 - Doopy
1
对于原始数组,无需递归,因为原始数组不能包含数组,所以您可以使用.flatMap(o -> o instanceof int[]? Arrays.stream((int[])o).boxed(): o instanceof Object[]? flatten((Object[])o): Stream.of(o));或者,总是映射到'int'值,public static IntStream flattenToInt(Object o) { return o instanceof int[]? Arrays.stream((int[])o): o instanceof Object[]? Arrays.stream((Object[])o) .flatMapToInt(x -> flattenToInt(x)): IntStream.of(((Number)o).intValue()); } - Holger
1
如果输入类型是像 int[][][] 这样的普通数组,那么操作会更简单,因为不需要递归,您只需进行 n-1flatMap 步骤来处理 n 维度。static IntStream flatten(int[][][] array) { return Arrays.stream(array).flatMap(Arrays::stream) .flatMapToInt(Arrays::stream); } - Holger
好的观点,但如果内部数组是混合类型,则所有情况的不同变得非常复杂。虽然我找不到更好的解决方案。 - Doopy
2
@DQQpy,如果你愿意,你可以使用java.lang.reflect.Array来通用处理所有数组类型:static Stream<Object> flatten(Object o) { return o != null && o.getClass().isArray()? IntStream.range(0, Array.getLength(o)).mapToObj(ix -> Array.get(o, ix)).flatMap(x -> flatten(x)): Stream.of(o); } - Holger

10

我使用Java创建了一个类来解决这个问题,下面也展示了代码。

解决方案:

package com.conorgriffin.flattener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Flattens an array of arbitrarily nested arrays of integers into a flat array of integers.
 * <p/>
 * @author conorgriffin
 */
public class IntegerArrayFlattener {

    /**
     * Flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
     *
     * @param inputArray an array of Integers or nested arrays of Integers
     * @return flattened array of Integers or null if input is null
     * @throws IllegalArgumentException
     */
    public static Integer[] flatten(Object[] inputArray) throws IllegalArgumentException {

        if (inputArray == null) return null;

        List<Integer> flatList = new ArrayList<Integer>();

        for (Object element : inputArray) {
            if (element instanceof Integer) {
                flatList.add((Integer) element);
            } else if (element instanceof Object[]) {
                flatList.addAll(Arrays.asList(flatten((Object[]) element)));
            } else {
                throw new IllegalArgumentException("Input must be an array of Integers or nested arrays of Integers");
            }
        }
        return flatList.toArray(new Integer[flatList.size()]);
    }
}

单元测试:

package com.conorgriffin.flattener;

import org.junit.Assert;
import org.junit.Test;

/**
 * Tests IntegerArrayFlattener
 */
public class IntegerArrayFlattenerTest {

    Integer[] expectedArray = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    @Test
    public void testNullReturnsNull() throws IllegalArgumentException {
        Assert.assertNull(
                "Testing a null argument",
                IntegerArrayFlattener.flatten(null)
        );
    }

    @Test
    public void testEmptyArray() throws IllegalArgumentException {
        Assert.assertArrayEquals(
                "Testing an empty array",
                new Integer[]{},
                IntegerArrayFlattener.flatten(new Object[]{})
        );
    }

    @Test
    public void testFlatArray() throws IllegalArgumentException {
        Assert.assertArrayEquals(
                "Testing a flat array",
                expectedArray,
                IntegerArrayFlattener.flatten(new Object[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
        );
    }

    @Test
    public void testNestedArray() throws IllegalArgumentException {
        Assert.assertArrayEquals(
                "Testing nested array",
                expectedArray,
                IntegerArrayFlattener.flatten(new Object[]{1, 2, 3, 4, new Object[]{5, 6, 7, 8}, 9, 10})
        );
    }

    @Test
    public void testMultipleNestedArrays() throws IllegalArgumentException {
        Assert.assertArrayEquals(
                "Testing multiple nested arrays",
                expectedArray,
                IntegerArrayFlattener.flatten(new Object[]{1, 2, new Object[]{3, 4, new Object[]{5}, 6, 7}, 8, 9, 10})
        );
    }

    @Test(expected = IllegalArgumentException.class)
    public void throwsExceptionForObjectInArray() throws IllegalArgumentException {
        IntegerArrayFlattener.flatten(
                new Object[]{new Object()}
        );
    }

    @Test(expected = IllegalArgumentException.class)
    public void throwsExceptionForObjectInNestedArray() throws IllegalArgumentException {
        IntegerArrayFlattener.flatten(
                new Object[]{1, 2, new Object[]{3, new Object()}}
        );
    }

    @Test(expected = IllegalArgumentException.class)
    public void throwsExceptionForNullInArray() throws IllegalArgumentException {
        IntegerArrayFlattener.flatten(
                new Object[]{null}
        );
    }

    @Test(expected = IllegalArgumentException.class)
    public void throwsExceptionForNullInNestedArray() throws IllegalArgumentException {
        IntegerArrayFlattener.flatten(
                new Object[]{1, 2, new Object[]{3, null}}
        );
    }

}

5

如果它是一个只有两个层级的原始数组,您可以这样做:

Arrays.stream(array)
  .flatMapToInt(o -> Arrays.stream(o))
  .toArray()

要获得相应的盒装数组(必要时可以取消盒装)


2

这是我解决问题的方式。 不知道你要寻求哪种效率。但是,在JavaScript中,这可以完成工作。

arr.toString().split(',').filter((item) => item).map((item) => Number(item))

可能更有效的方法是使用reduce和concat方法从arr中进行递归。

function flattenDeep(arr1) {
   return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}

你可以直接使用 array.flat(Infinity),这样更加简洁。 - Johann

1

它可以通过迭代方法被压平。

static class ArrayHolder implements Iterator<Object> {
    private final Object[] elements;
    private int index = -1;

    public ArrayHolder(final Object[] elements) {
        this.elements = elements;
    }

    @Override
    public boolean hasNext() {
        return Objects.nonNull(elements) && ++index < elements.length;
    }

    @Override
    public Object next() {
        if (Objects.isNull(elements) || (index == -1 || index > elements.length))
            throw new NoSuchElementException();

        return elements[index];
    }
}


private static boolean hasNext(ArrayHolder current) {
    return Objects.nonNull(current) && current.hasNext();
}

private void flat(Object[] elements, List<Object> flattened) {
    Deque<ArrayHolder> stack = new LinkedList<>();
    stack.push(new ArrayHolder(elements));

    ArrayHolder current = null;
    while (hasNext(current)
            || (!stack.isEmpty() && hasNext(current = stack.pop()))) {
        Object element = current.next();

        if (Objects.nonNull(element) && element.getClass().isArray()) {
            Object[] e = (Object[]) element;
            stack.push(current);
            stack.push(new ArrayHolder(e));
            current = null;
        } else {
            flattened.add(element);
        }
    }
}

你可以在这里找到完整的源代码here 你可以使用递归来解决这个问题。
private void flat(Object[] elements, List<Object> flattened) {
    for (Object element : elements)
    {
        if (Objects.nonNull(element) && element.getClass().isArray())
        {
            flat((Object[])element, flattened);
        }
        else
        {
            flattened.add(element);
        }
    }
}

这是关于 递归 的链接。

1
这是我在Java中解决这个问题的方法:
public class ArrayUtil {

    /**
     * Utility to flatten an array of arbitrarily nested arrays of integers into
     * a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]
     * @param inputList
     */
    public static Integer[] flattenArray(ArrayList<Object> inputList) {

        ArrayList<Integer> flatten = new ArrayList<Integer>();
        if (inputList.size() <= 0) {
            return new Integer[0];                          // if the inputList is empty, return an empty Integer[] array.
        }

        for (Object obj : inputList) {
            recursiveFlatten(flatten, obj);                 // otherwise we can recursively flatten the input list.
        }

        Integer [] flatArray = new Integer[flatten.size()];
        return flatArray = flatten.toArray(flatArray);      
    }

    /**
     * Recursively flatten a nested array.
     * @param flatten
     * @param o
     */
    private static void recursiveFlatten(ArrayList<Integer> flatten, Object o){
        if(isInteger(o)){                               // if the object is of type Integer, just add it into the list.
            flatten.add((Integer)o);
        } else if(o instanceof ArrayList){              // otherwise, we need to call to recursively flatten the array
            for(Object obj : (ArrayList<Object>) o){    // for the case where there are deeply nested arrays.
                recursiveFlatten(flatten, obj);
            }
        }
    }

    /**
     * Return true if object belongs to Integer class,
     * else return false.
     * @param obj
     * @return
     */
    private static boolean isInteger(Object obj) {
        return obj instanceof Integer;
    }

}

1

递归调用方法对于这种情况是可行的:

private static void recursiveCall(Object[] array) {

        for (int i=0;i<array.length;i++) {
            if (array[i] instanceof Object[]) {
                recursiveCall((Object[]) array[i]);
            }else {
                System.out.println(array[i]);
            }
            
    }
        
}

0

包 com.app;

导入 java.util.Arrays;

公共类 Test2 {

public static void main(String[] args) {

    Object arr[] = { 1, 2, new Object[] { 4, new int[] { 5, 6 }, 7 }, 10 };
    String deepToString = Arrays.deepToString(arr);
    String replace = deepToString.replace("[", "").replace("]", "");
    String array[] = replace.split(",");
    int temp[] = new int[array.length];
    for (int i = 0; i < array.length; i++) {
        temp[i] = Integer.parseInt(array[i].trim());
    }
    System.out.println(Arrays.toString(temp));
}

}


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

-5
您可以尝试这段代码:
String a = "[[[1],2],[3]],4] ";
a= a.replaceAll("[(\\[|\\])]", "");
String[] b = a.split(",");

1
OP有一个数组,而你返回了字符串而不是数组。 - Michu93

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接