Java:将按字符串长度排序的字符串数组拆分为按字符串长度划分的多个数组

时间:2020-04-29 20:19:02

标签: java arrays matrix split sub-array

我目前有一个字符串数组,例如,按字符串长度排序:

String[] array = [a,b,c,ab,cd,abc,abcde,fghij,klmno]

在跟踪每个数组的字符串大小是多少的同时,如何根据字符串大小将其转换为几个数组?我想要的是:

String[] array1 = [a,b,c]
String[] array2 = [ab,cd]
String[] array3 = [abc]
String[] array5 = [abcde,fghij,klmno]

我可能正在考虑为此使用矩阵,但不知道要这样做。

5 个答案:

答案 0 :(得分:2)

最好创建一个Map<Integer, List<String>>,其中key是字符串的长度,值是similair大小的字符串的列表。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SimpleArray {

    public static void main(String[] args) {
        String[] array = new String[]{"a","b","c","ab","cd","abc","abcde","fghij","klmno"};

        Map<Integer, List<String>> map = new HashMap<>();

        for (int i = 0; i < array.length; i++) {
            List< String> temp = map.getOrDefault(array[i].length(),new ArrayList<>());
            temp.add(array[i]);
            map.put(array[i].length(),temp);
        }
        System.out.println(map);

    }
}

答案 1 :(得分:1)

要快速访问,您还可以使用列表列表。

String[] array = new String[]{"a","b","c","ab","cd","abc","abcde","fghij","klmno"};
List<List<String>> lists = new LinkedList<>();

// you will have to update this number based on the maximum length of string you are expecting
for (int i = 0; i < 6; i++) {
    lists.add(new LinkedList<>());
}

for (String a: array) {
    lists.get(a.length()).add(a);
}

System.out.println(lists);

这里,第一个列表用于大小,而内部列表用于实际字符串。

注意:这仅适用于较小的字符串。如果您具有长度为1、2、100的字符串。您可能应该使用HashMaps,因为这种方法会浪费很多内存。


使用Java8:

String[] array = new String[]{"a","b","c","ab","cd","abc","abcde","fghij","klmno"};

List<List<String>> lists = IntStream.range(0, 6).<List<String>>mapToObj(
    i -> new LinkedList<>()).collect(Collectors.toCollection(LinkedList::new));

Arrays.stream(array).forEach(a -> lists.get(a.length()).add(a));

System.out.println(lists);

答案 2 :(得分:1)

我的解决方案,与@QuickSilver唯一不一样的是。 现在我在这里,我也放了我的东西,因为我有专门的时间,但我再说一遍,我建议跟随他。

CODE

public static void main(String[] args) {
        String[] array = {"a", "b", "c", "ab", "cd", "abc", "abcde", "fghij", "klmdfwetdfgdfgdfgdg"};
        HashMap<Integer, List<String>> hashMap = new HashMap<>();
        int strLength = array[0].length();

        for (String s : array) {
            while (true) {
                if (s.length() == strLength) {
                    if (hashMap.get(strLength) != null) {
                        List<String> temp = hashMap.get(strLength);
                        temp.add(s);
                        hashMap.put(strLength, temp);
                    } else {
                        List<String> strings = new LinkedList<>();
                        strings.add(s);
                        hashMap.put(strLength, strings);
                    }
                    break;
                } else
                    strLength = s.length();
            }
        }
        System.out.println(hashMap);
    }

答案 3 :(得分:1)

使用System:arraycopy

仅使用阵列的解决方案:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String[][] arraysList = new String[1][];
        String[] array = { "a", "b", "c", "ab", "cd", "abc", "abcde", "fghij", "klmno" };
        int srcPos, row = 0;
        for (int i = 0; i < array.length; i++) {
            srcPos = i;
            while (i < array.length - 1 && array[i].length() == array[i + 1].length()) {
                i++;
            }
            // Create a new array to store the current set of strings of equal length
            String[] subarray = new String[i - srcPos + 1];

            // Copy the current set of strings of equal length from array to subarray[]
            System.arraycopy(array, srcPos, subarray, 0, subarray.length);

            // Assign subarray[] to arraysList[][]
            arraysList[row++] = subarray;

            // Copy arraysList[][] to temp [][], increase size of arraysList[][] and restore
            // arrays from temp [][] to arraysList[][]
            String[][] temp = arraysList;
            arraysList = new String[row + 1][subarray.length];
            for (int j = 0; j < temp.length; j++) {
                arraysList[j] = temp[j];
            }
        }

        // Drop the last row which was created to store a new subarray but there was no
        // more subarrays to store and therefore it is empty.
        arraysList = Arrays.copyOf(arraysList, arraysList.length - 1);

        // Display the subarrays
        for (String[] arr : arraysList) {
            System.out.println(Arrays.toString(arr));
        }
    }
}

输出:

[a, b, c]
[ab, cd]
[abc]
[abcde, fghij, klmno]

使用List和数组的解决方案:

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

public class Main {
    public static void main(String[] args) {
        List<String[]> list = new ArrayList<String[]>();
        String[] array = { "a", "b", "c", "ab", "cd", "abc", "abcde", "fghij", "klmno" };
        int srcPos;
        for (int i = 0; i < array.length; i++) {
            srcPos = i;
            while (i < array.length - 1 && array[i].length() == array[i + 1].length()) {
                i++;
            }
            String[] subarray = new String[i - srcPos + 1];
            System.arraycopy(array, srcPos, subarray, 0, subarray.length);
            list.add(subarray);
        }

        // Display the subarrays
        for (String[] arr : list) {
            System.out.println(Arrays.toString(arr));
        }
    }
}

输出:

[a, b, c]
[ab, cd]
[abc]
[abcde, fghij, klmno]

答案 4 :(得分:1)

您可以使用Map将字符串长度与该长度的字符串子数组关联:

String[] array = {"a", "b", "c", "ab", "cd", "abc", "abcde", "fghij", "klmno"};

Map<Integer, String[]> map = new HashMap<>();

for(int j=0, i=1; i<=array.length; i++)
{
    if(i == array.length || array[i].length() > array[j].length())
    {
        map.put(array[j].length(), Arrays.copyOfRange(array, j, i)) ;
        j = i;
    }
}

for(Integer len: map.keySet())
    System.out.format("%d : %s%n", len, Arrays.toString(map.get(len)));

输出:

1 : [a, b, c]
2 : [ab, cd]
3 : [abc]
5 : [abcde, fghij, klmno]
相关问题