简体   繁体   中英

Java: Split array of strings sorted by string length into several arrays by string length

I currently have an array of strings that is sorted by string length for example:

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

How would turn this array into several arrays depending on string size while keeping track of what the string size for each array is? What I want is:

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

I was maybe thinking of using a matrix for this but have no idea of going about doing this.

Better to create a Map<Integer, List<String>> where key is length of the string and value is the list of similair sized strings.

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

    }
}

For quick access, you can also use a list of lists.

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

Here, the first list is for the size and the inner list is for the actual strings.

Note: this is only for smaller strings. If you have strings of length 1, 2, 100. You should probably go with HashMaps because you will have a lot of memory wasted in this approach.


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

My solution is the same as @QuickSilver's only that much less clear . Now that I'm here, I place mine as well because I have dedicated time to it, but I repeat, I recommend following his.

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

Use System:arraycopy

Solution using arrays only:

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

Output:

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

Solution using List and array:

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

Output:

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

You can use a Map to associate string lengths to the sub-array of strings of that length:

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

Output:

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

You can also use a list:

List<String> originalList = Arrays.asList("a","b","c","ab","cd","abc","abcde","fghij","klmno");

Map<?,?> m = originalList.stream().collect(Collectors.groupingBy(String::length));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM