java中的嵌套数组

pxiryf3j  于 2023-01-07  发布在  Java
关注(0)|答案(9)|浏览(245)

我想把嵌套的数组变平,比如:

[[[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));
}
yyyllmsg

yyyllmsg1#

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));
jhdbpxl9

jhdbpxl92#

我使用Java创建了a class to solve this,代码如下所示。
溶液:

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}}
        );
    }

}
vmdwslir

vmdwslir3#

如果它是一个只有两层的基元数组,你可以这样做:

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

以获取相应的装箱数组(如有必要,可以取消装箱)

oknrviil

oknrviil4#

这就是我解决问题的方法。不知道你想要哪种效率。但是是的。这在JavaScript中做得很好。
第一个月
一种可能更有效方法是使用arr和递归中的reduce和concat方法。

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

alen0pnh5#

下面是我在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;
    }

}
hmtdttj4

hmtdttj46#

它可以通过迭代的方法来展平。

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);
        }
    }
}

下面是recursion的链接。

vecaoik1

vecaoik17#

递归调用方法适用于这种情况:

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]);
            }
            
    }
        
}
ffscu2ro

ffscu2ro8#

软件包com.app;
导入java.util数组;
公共类Test 2 {

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));
}

}

yhxst69z

yhxst69z9#

你可以试试这个代码:

String a = "[[[1],2],[3]],4] ";
a= a.replaceAll("[(\\[|\\])]", "");
String[] b = a.split(",");

相关问题