2015-08-06 3 views
0

Я хочу, чтобы сгладить вложенные массивы, как:Свести вложенные массивы в Java

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

вручную в Java я не могу найти ключ! : S

Я попробовал руководство Java Script, но он не получает решение

+3

Это вопрос Javascript. Это не имеет смысла в Java. – dotvav

+0

Я хочу решить его на любом языке, java или javascript – mhGaber

+0

Мы действительно хотим помочь, но я, например, не понимаю, о чем вы просите. cn вы даете пример Java для ввода и желаемого вывода? –

ответ

0

вы можете попробовать этот код:

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

я создал a class to solve this с использованием 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}} 
     ); 
    } 

} 
0

Это, как я решил эту проблему в 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; 
    } 

} 
2

Java 8 в поток API предлагает компактное и гибкое решение , Использование метода

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(flat)); 
Смежные вопросы