Java 如何按数组索引分组

Java 如何按数组索引分组,java,arrays,hashmap,Java,Arrays,Hashmap,我试图用索引除以4对元素数组进行分组。例如,在下面的输入中,由于int_arr的索引除以4返回0、0、0、1、1、1、1、2、2、2,我希望将它们分组到str_arr中的元素下,其中A对应于int_arr中的元素1、2、3、4,以此类推 我知道我需要将int_arr中的元素转换为字符串,并且我还需要一个映射来保存所有元素,以便str_arr中的元素是键,int_arr中的串联元素是值。然而,我很难根据元素的索引除以4来对元素进行分组,我需要对此有所了解 输入: int[] int_arr = {

我试图用索引除以4对元素数组进行分组。例如,在下面的输入中,由于int_arr的索引除以4返回0、0、0、1、1、1、1、2、2、2,我希望将它们分组到
str_arr
中的元素下,其中A对应于
int_arr
中的元素1、2、3、4,以此类推

我知道我需要将
int_arr
中的元素转换为字符串,并且我还需要一个映射来保存所有元素,以便
str_arr
中的元素是键,
int_arr
中的串联元素是值。然而,我很难根据元素的索引除以4来对元素进行分组,我需要对此有所了解

输入:

int[] int_arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12};
String[] str_arr = {A, B, C, D};
期望输出:

{A= 1, 2, 3, 4, B = 5, 6, 7, 8, C = 9, 19, 11, 12}

如果我正确理解了你的问题,你需要这样的东西:

int outputLength = (int)Math.ceil((double)int_arr.length / 4);
String[] output = new String[outputLength];

int i = 0;
int integerPart = 0;

for(String label: str_arr) {
    if(i >= int_arr.length) break;
        
    StringBuilder group = new StringBuilder();
    group.append(label + "= ");

    while(i < int_arr.length && i / 4 == integerPart) {
        group.append(int_arr[i]);
        ++i;
        
        if(i / 4 == integerPart) {
            group.append(", ");
        }
    }
    
    output[integerPart] = group.toString();
    integerPart++;
}
int outputLength=(int)Math.ceil((double)int_arr.length/4);
字符串[]输出=新字符串[outputLength];
int i=0;
整数部分=0;
用于(字符串标签:str_arr){
如果(i>=内部阵列长度)中断;
StringBuilder组=新建StringBuilder();
追加(标签+“=”);
而(i
所需的输出类似于一个映射,其中键取自
str\u arr
,值-子数组或子列表取自
int\u arr
。为此目的,可以方便地使用流API:

Map result=IntStream.range(0,(int)Math.ceil(int_arr.length/4.0))
.boxed()
.collect(collector.toMap)(
i->str_arr[i],
i->Arrays.copyOfRange(int_arr,i*4,Math.min(i*4+4,int_arr.length))
));
result.forEach((k,v)->System.out.printf(“%s->%s%n”,k,array.toString(v));
输出:

A -> [1, 2, 3, 4]
B -> [5, 6, 7, 8]
C -> [9, 10, 11, 12]
{A=[1, 2, 3, 4], B=[5, 6, 7, 8], C=[9, 10, 11, 12]}
要获取列表,可以使用另一个流和
收集器::toList
代替
数组::copyOfRange

Map-mapOfLists=IntStream.range(0,(int)Math.ceil(int_arr.length/4.0))
.boxed()
.collect(collector.toMap)(
i->str_arr[i],
i->IntStream.range(i*4,Math.min(i*4+4,int_arr.length))
.mapToObj(j->int_arr[j])
.collect(收集器.toList())
));
System.out.println(MapofList);
输出:

A -> [1, 2, 3, 4]
B -> [5, 6, 7, 8]
C -> [9, 10, 11, 12]
{A=[1, 2, 3, 4], B=[5, 6, 7, 8], C=[9, 10, 11, 12]}

我假设您可以将一维整数数组拆分为二维对象数组,其中该二维数组的每个行的第一个元素包含自动生成的大写字母前缀字符串(从字母a开始),其余的元素包含拆分整数数组中的整数值。换句话说,如果您有一个整数(int[])数组,它由12个整数元素组成:

int[] int_arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
如果您想按顺序将此数组分为4段,那么最终将得到一个二维对象数组(对象[][]),该数组由3行组成,每行包含5列。请始终记住,第一列可以选择性地保留为前缀字符串:

[ [A, 1, 2, 3, 4], 
  [B, 5, 6, 7, 8], 
  [C, 9, 10, 11, 12] ]
但是,如果提供的int[]数组包含14整数元素,并且不能被4等分,该怎么办?然后在二维数组中创建第四行,该行仅包含3列,例如:

[ [A, 1, 2, 3, 4], 
  [B, 5, 6, 7, 8], 
  [C, 9, 10, 11, 12],
  [D, 13, 14] ]
但是如果int[]数组中有26个以上的整数元素,比如说121或更多的整数元素呢?当前缀自动生成器传递字母Z时,每行的前缀字符串是什么?前缀自动生成器然后生成以下前缀字符串:

AA, AB, AC, ..., AZ, 
BA, BB, BC, ..., BZ,
...................,
ZA, ZB, ZC, ..., ZZ,
AAA, AAB, AAC, ..., AAZ,
and so on, and so on...
以下名为splitIntArrayTo2DArrayWithLetterPrefix()的Java方法将执行此操作。是的…我知道这是一个疯狂的长名字,但它是为这个特定的目的描述性的。您可以随时将其更改为您喜欢的任何内容:

/**
 * Creates a two dimensional Object array (Object[][]) from a supplied
 * single dimensional integer array (int[]) based on the supplied desired
 * number of columns for each row of the created 2D Array. The first element
 * of every row within the newly created 2D array will be a string letter
 * prefix starting from the letter 'A'. So if we have an integer array which
 * consists of:
 * <pre>
 *
 *    int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};</pre><br>
 * <p>
 * and we want to split this single dimensional array into a 2D array with
 * each row consisting of 3 columns which will actually be 4 columns because
 * the column index 0 of each row is reserved for an auto generated prefix
 * string. When this above int[] array is run through this method the return
 * 2D Object[] array will consist of:
 * <pre>
 *
 *     [A, 1, 2, 3]
 *     [B, 4, 5, 6]
 *     [C, 7, 8, 9]
 *     [D, 10, 11, 12]</pre><br>
 * <p>
 * If the single dimensional int[] array is large enough whereas the rows
 * span greater than to handle the prefix string of A to Z then the prefix
 * string automatically changes to AA to ZZ, then to AAA to ZZZ, then to
 * AAAA to ZZZZ, and so on. When the rows get to a 4 letter prefix string
 * then we're talking about several thousands of Array elements.
 *
 * @param int_arr         (Single Dimensional int[] Array) The integer array
 *                        to split.<br><br>
 *
 * @param desiredColumns  (Integer - int) The desired number of columns to
 *                        be contained within the created 2D array for each
 *                        array row. If during processing the final elements
 *                        of the int[] array does not mean the desired
 *                        columns requirement then the last row of the
 *                        returned 2D Object[][] array will contain those
 *                        elements, for example, if the supplied int[] array
 *                        contained 13 elements<pre>
 *
 *    int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};</pre><br>
 *
 * and we want to split this array into a 2D array with each row consisting
 * of 3 columns then our returned 2D Object[] array will consist of:
 * <pre>
 *
 *     [A, 1, 2, 3]
 *     [B, 4, 5, 6]
 *     [C, 7, 8, 9]
 *     [D, 10, 11, 12]
 *     [E, 13]</pre><br>
 *
 * Notice the last row, it only consists of 2 elements instead of 4 (the
 * prefix string and the final int[] array element). No array element is
 * ignored within the supplied int[] array. All elements are placed into the
 * 2D Object[][] array even if the column count for the last row is
 * short.<br>
 *
 * @param dontApplyPrefix (Optional - Boolean) Default is false. By default
 *                        the first element in each 2D array row (at index
 *                        0) is reserved for a auto-generated letter prefix
 *                        string. If true is supplied then no letter prefix
 *                        string is applied to the returned 2D Object[][]
 *                        Array, the int[] array is merely split into 
 *                        individual columnar rows as specified by the 
 *                        desiredColumns parameter argument. Nothing, true, 
 *                        false, or null can be supplied to this optional 
 *                        parameter.
 *
 * @return (Two Dimensional Object[][] Array) The created 2D Object Array.
 */
public static Object[][] splitIntArrayTo2DArrayWithLetterPrefix(int[] int_arr,
                int desiredColumns, Boolean... dontApplyPrefix) {
    boolean noPrefix = false;
    if (dontApplyPrefix != null && dontApplyPrefix.length > 0) {
        noPrefix = dontApplyPrefix[0];
    }
    if (int_arr.length == 0 || (desiredColumns < 1 && desiredColumns > int_arr.length)) {
        return null;
    }
    int availableRows = int_arr.length % desiredColumns == 0
            ? (int_arr.length / desiredColumns)
            : int_arr.length / desiredColumns + 1;

    Object[][] newArray = new Object[availableRows][];
    Object[] innerArray = new Object[!noPrefix ? desiredColumns + 1 : desiredColumns];
    String rowPrefix = "";
    int columnCount = 0;
    int rowCount = 0;
    for (int i = 0; i < int_arr.length; i++) {
        if (columnCount == 0 && !noPrefix) {
            /* Generate a row prefix letter string for the first column of row.
               The prefix letter will always start with 'A' and increment up
               the alphabet for each new array row until 'Z' is reached at which
               point the prefix changes to 'AA', then 'AB' for the next row and
               so on until the the array creation has completed.            */
            int val = rowCount;
            StringBuilder sb = new StringBuilder(String.valueOf((char) ('A' + (val % 26))));
            while ((val = (val / 26 - 1)) >= 0) {
                sb.append((char) ('A' + (val % 26)));
            }
            rowPrefix = sb.reverse().toString();
            innerArray[columnCount] = rowPrefix;
            columnCount++;
        }
        innerArray[columnCount] = int_arr[i];
        columnCount++;
        if (!noPrefix ? columnCount > desiredColumns : columnCount == desiredColumns) {
            newArray[rowCount] = innerArray;
            innerArray = new Object[noPrefix && int_arr.length - (i + 1) < desiredColumns ? int_arr.length - (i + 1) : noPrefix ? desiredColumns : int_arr.length - (i + 1) < desiredColumns ? int_arr.length - i : desiredColumns + 1];
            columnCount = 0;
            rowCount++;
        }
    }
    if (innerArray.length > 0 && innerArray[0] != null) {
        newArray[rowCount] = innerArray;
    }
    return newArray;
}
显示返回的数组:

System.out.println("Desired display as per Original Post:");
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < myArray.length; i++) {
    String elementalString = Arrays.toString(myArray[i]);
    elementalString = elementalString.substring(elementalString.indexOf(",") + 1,
            elementalString.lastIndexOf("]")).trim();
    if (!sb.toString().isEmpty()) { 
        sb.append(", "); 
    }
    sb.append(myArray[i][0].toString()).append(dontUseAutoPrefix ? ", " : " = ")
              .append(elementalString);
}
System.out.println(sb.toString());
Desired display as per Original Post:
A = 1, 2, 3, 4, B = 5, 6, 7, 8, C = 9, 10, 11, 12
以任意方式显示返回的数组:

System.out.println("Desired display as per Original Post:");
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < myArray.length; i++) {
    String elementalString = Arrays.toString(myArray[i]);
    elementalString = elementalString.substring(elementalString.indexOf(",") + 1,
            elementalString.lastIndexOf("]")).trim();
    if (!sb.toString().isEmpty()) { 
        sb.append(", "); 
    }
    sb.append(myArray[i][0].toString()).append(dontUseAutoPrefix ? ", " : " = ")
              .append(elementalString);
}
System.out.println(sb.toString());
Desired display as per Original Post:
A = 1, 2, 3, 4, B = 5, 6, 7, 8, C = 9, 10, 11, 12

请包括您目前拥有的代码。